SSM框架整合学习笔记
总体思路:Spring框架来整合另外两个框架。
环境搭建
步骤1:创建一个ssm数据库,其中创建一个account表格,包含name,age,money三个字段。代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 CREATE DATABASE ssm; 2 USE ssm; 3 CREATE TABLE account( 4 id INT PRIMARY KEY AUTO_INCREMENT, 5 NAME VARCHAR(20), 6 money DOUBLE 7 );
步骤2:创建一个maven工程,选择webapp骨架
步骤3:在pom.xml中导入需要的坐标
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>org.example</groupId> 8 <artifactId>SSM</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>SSM Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 18 <maven.compiler.source>1.8</maven.compiler.source> 19 <maven.compiler.target>1.8</maven.compiler.target> 20 <spring.version>5.0.2.RELEASE</spring.version> 21 <slf4j.version>1.6.6</slf4j.version> 22 <log4j.version>1.2.12</log4j.version> 23 <mysql.version>5.1.6</mysql.version> 24 <mybatis.version>3.4.5</mybatis.version> 25 </properties> 26 27 <dependencies> 28 <!-- spring --> 29 <dependency> 30 <groupId>org.aspectj</groupId> 31 <artifactId>aspectjweaver</artifactId> 32 <version>1.6.8</version> 33 </dependency> 34 <dependency> 35 <groupId>org.springframework</groupId> 36 <artifactId>spring-aop</artifactId> 37 <version>${spring.version}</version> 38 </dependency> 39 <dependency> 40 <groupId>org.springframework</groupId> 41 <artifactId>spring-context</artifactId> 42 <version>${spring.version}</version> 43 </dependency> 44 <dependency> 45 <groupId>org.springframework</groupId> 46 <artifactId>spring-web</artifactId> 47 <version>${spring.version}</version> 48 </dependency> 49 <dependency> 50 <groupId>org.springframework</groupId> 51 <artifactId>spring-webmvc</artifactId> 52 <version>${spring.version}</version> 53 </dependency> 54 <dependency> 55 <groupId>org.springframework</groupId> 56 <artifactId>spring-test</artifactId> 57 <version>${spring.version}</version> 58 </dependency> 59 <dependency> 60 <groupId>org.springframework</groupId> 61 <artifactId>spring-tx</artifactId> 62 <version>${spring.version}</version> 63 </dependency> 64 <dependency> 65 <groupId>org.springframework</groupId> 66 <artifactId>spring-jdbc</artifactId> 67 <version>${spring.version}</version> 68 </dependency> 69 <dependency> 70 <groupId>junit</groupId> 71 <artifactId>junit</artifactId> 72 <version>4.12</version> 73 <scope>compile</scope> 74 </dependency> 75 <dependency> 76 <groupId>mysql</groupId> 77 <artifactId>mysql-connector-java</artifactId> 78 <version>${mysql.version}</version> 79 </dependency> 80 <dependency> 81 <groupId>javax.servlet</groupId> 82 <artifactId>servlet-api</artifactId> 83 <version>2.5</version> 84 <scope>provided</scope> 85 </dependency> 86 <dependency> 87 <groupId>javax.servlet.jsp</groupId> 88 <artifactId>jsp-api</artifactId> 89 <version>2.0</version> 90 <scope>provided</scope> 91 </dependency> 92 <dependency> 93 <groupId>jstl</groupId> 94 <artifactId>jstl</artifactId> 95 <version>1.2</version> 96 </dependency> 97 <!-- log start --> 98 <dependency> 99 <groupId>log4j</groupId> 100 <artifactId>log4j</artifactId> 101 <version>${log4j.version}</version> 102 </dependency> 103 <dependency> 104 <groupId>org.slf4j</groupId> 105 <artifactId>slf4j-api</artifactId> 106 <version>${slf4j.version}</version> 107 </dependency> 108 <dependency> 109 <groupId>org.slf4j</groupId> 110 <artifactId>slf4j-log4j12</artifactId> 111 <version>${slf4j.version}</version> 112 </dependency> 113 <!-- log end --> 114 <dependency> 115 <groupId>org.mybatis</groupId> 116 <artifactId>mybatis</artifactId> 117 <version>${mybatis.version}</version> 118 </dependency> 119 <dependency> 120 <groupId>org.mybatis</groupId> 121 <artifactId>mybatis-spring</artifactId> 122 <version>1.3.0</version> 123 </dependency> 124 <dependency> 125 <groupId>c3p0</groupId> 126 <artifactId>c3p0</artifactId> 127 <version>0.9.1.2</version> 128 <type>jar</type> 129 <scope>compile</scope> 130 </dependency> 131 </dependencies> 132 133 <build> 134 <finalName>SSM</finalName> 135 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 136 <plugins> 137 <plugin> 138 <artifactId>maven-clean-plugin</artifactId> 139 <version>3.1.0</version> 140 </plugin> 141 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> 142 <plugin> 143 <artifactId>maven-resources-plugin</artifactId> 144 <version>3.0.2</version> 145 </plugin> 146 <plugin> 147 <artifactId>maven-compiler-plugin</artifactId> 148 <version>3.8.0</version> 149 </plugin> 150 <plugin> 151 <artifactId>maven-surefire-plugin</artifactId> 152 <version>2.22.1</version> 153 </plugin> 154 <plugin> 155 <artifactId>maven-war-plugin</artifactId> 156 <version>3.2.2</version> 157 </plugin> 158 <plugin> 159 <artifactId>maven-install-plugin</artifactId> 160 <version>2.5.2</version> 161 </plugin> 162 <plugin> 163 <artifactId>maven-deploy-plugin</artifactId> 164 <version>2.8.2</version> 165 </plugin> 166 </plugins> 167 </pluginManagement> 168 </build> 169 </project>
步骤4:补全main目录,在java目录下创建各个层的包与接口,类文件,结构如下:
注意:domain中的Account是一个与数据库account表格对应的JabaBean。
编写Spring框架
步骤1:resource包中放入log4j配置文件,并创建applicationContext.xml配置文件,在其中开启注解扫描,并设置忽略扫描Controller注解。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx.xsd"> 15 <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架 16 去管理 --> 17 <context:component-scan base-package="fdx"> 18 <!-- 配置要忽略的注解 --> 19 <context:exclude-filter type="annotation" 20 expression="org.springframework.stereotype.Controller"/> 21 </context:component-scan> 22 </beans>
步骤2:在service层实现类AccountServiceImpl中加@Service注解。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.service.impl; 2 3 import fdx.domain.Account; 4 import fdx.service.IAccountService; 5 import org.springframework.stereotype.Service; 6 7 import java.util.List; 8 //该注解表示把service交给ioc管理 9 @Service("accountService") 10 public class AccountServiceImpl implements IAccountService { 11 12 @Override 13 public List<Account> findAll() { 14 System.out.println("业务层:查询所有账户"); 15 return null; 16 } 17 18 @Override 19 public void saveAccount(Account account) { 20 System.out.println("业务层:保存账户"); 21 22 } 23 }
步骤3:进行测试。java/fdx中建立一个test包,写一个TestSpring类进行测试。加载配置文件,获取service对象,执行findAll方法。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.test; 2 3 import fdx.service.IAccountService; 4 import org.junit.Test; 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7 8 public class TestSpring { 9 @Test 10 public void run1(){ 11 //加载配置文件 12 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 13 //获取对象 14 IAccountService as = (IAccountService) ac.getBean("accountService"); 15 as.findAll(); 16 17 18 } 19 }
运行结果:业务层:查询所有账户(打印了我们在service实现类AccountServiceImpl中执行方法后打印的语句)
编写SpringMVC框架
步骤1:配置webapp/WEB-INF/web.xml。配置前端控制器,创建DispatcherServlet对象,加载springmvc.xml配置文件(步骤2中编写),配置解决中文乱码的过滤器。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 !DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app> 6 <display-name>Archetype Created Web Application</display-name> 7 <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 --> 8 <servlet> 9 <servlet-name>dispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 --> 12 <init-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath:springmvc.xml</param-value> 15 </init-param> 16 <!-- 服务器启动的时候,让DispatcherServlet对象创建 --> 17 <load-on-startup>1</load-on-startup> 18 </servlet> 19 <servlet-mapping> 20 <servlet-name>dispatcherServlet</servlet-name> 21 <url-pattern>/</url-pattern> 22 </servlet-mapping> 23 <!-- 配置解决中文乱码的过滤器 --> 24 <filter> 25 <filter-name>characterEncodingFilter</filter-name> 26 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 27 <init-param> 28 <param-name>encoding</param-name> 29 <param-value>UTF-8</param-value> 30 </init-param> 31 </filter> 32 <filter-mapping> 33 <filter-name>characterEncodingFilter</filter-name> 34 <url-pattern>/*</url-pattern> 35 </filter-mapping> 36 37 </web-app>
步骤2:创建resource/springmvc.xml配置文件。扫描controller的注解,配置视图解析器,设置静态资源不过滤,开启对SpringMVC注解的支持。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:mvc="http://www.springframework.org/schema/mvc" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context.xsd"> 13 <!-- 扫描controller的注解,别的不扫描 --> 14 <context:component-scan base-package="fdx"> 15 <context:include-filter type="annotation" 16 expression="org.springframework.stereotype.Controller"/> 17 </context:component-scan> 18 <!-- 配置视图解析器 --> 19 <bean id="viewResolver" 20 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 21 <!-- JSP文件所在的目录 --> 22 <property name="prefix" value="/WEB-INF/pages/" /> 23 <!-- 文件的后缀名 --> 24 <property name="suffix" value=".jsp" /> 25 </bean> 26 <!-- 设置静态资源不过滤 --> 27 <mvc:resources location="/css/" mapping="/css/**" /> 28 <mvc:resources location="/images/" mapping="/images/**" /> 29 <mvc:resources location="/js/" mapping="/js/**" /> 30 <!-- 开启对SpringMVC注解的支持 --> 31 <mvc:annotation-driven /> 32 33 </beans>
步骤3:重新生成一个webapp/index.jsp页面,添加一个超链接。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <a href="account/findAll">测试</a> 8 </body> 9 </html>
步骤4:编写AccountController,添加@Controller注解和二级@Request注解指明index中设置的路径。方法体中打印"表现层:查询所有账户"。并返回list(步骤5中编写)。
步骤5:webapp/WEB-INF中创建一个pages包,创建一个list.jsp,里面打印一句“查询所有账户”即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <h3>查询所有账户</h3> 8 </body> 9 </html>
部署服务器后,可以看到主页面的超链接“测试”与跳转页面“查询所有账户”的效果,控制台会输出:表现层:查询所有账户
Spring整合SpringMVC的框架
目的:在controller中能成功地调用service对象中的方法。
步骤1:在项目启动的时候,就去加载applicationContext.xml的配置文件。
在web.xml中配置ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app> 6 <display-name>Archetype Created Web Application</display-name> 7 <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 --> 8 <servlet> 9 <servlet-name>dispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 --> 12 <init-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath:springmvc.xml</param-value> 15 </init-param> 16 <!-- 服务器启动的时候,让DispatcherServlet对象创建 --> 17 <load-on-startup>1</load-on-startup> 18 </servlet> 19 <servlet-mapping> 20 <servlet-name>dispatcherServlet</servlet-name> 21 <url-pattern>/</url-pattern> 22 </servlet-mapping> 23 <!-- 配置解决中文乱码的过滤器 --> 24 <filter> 25 <filter-name>characterEncodingFilter</filter-name> 26 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 27 <init-param> 28 <param-name>encoding</param-name> 29 <param-value>UTF-8</param-value> 30 </init-param> 31 </filter> 32 <filter-mapping> 33 <filter-name>characterEncodingFilter</filter-name> 34 <url-pattern>/*</url-pattern> 35 </filter-mapping> 36 <!-- 配置Spring的监听器 --> 37 <listener> 38 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 39 </listener> 40 <!-- 配置加载类路径的配置文件 --> 41 <context-param> 42 <param-name>contextConfigLocation</param-name> 43 <param-value>classpath:applicationContext.xml</param-value> 44 </context-param> 45 46 </web-app>
步骤2:在AccoutController中注入service对象并添加@Autowired注解,调用service对象的方法进行测试。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.controller; 2 3 import fdx.service.IAccountService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 @Controller 8 @RequestMapping("/account") 9 public class AccountController { 10 @Autowired 11 private IAccountService accoutService; 12 @RequestMapping("/findAll") 13 public String findAll() { 14 System.out.println("表现层:查询所有账户"); 15 accoutService.findAll(); 16 return "list"; 17 } 18 }
运行结果:点击网页超链接,成功跳转。控制台输出:
表现层:查询所有账户
业务层:查询所有账户
说明我们成功地调用了service对象中saveAccount()方法。
编写MyBatis框架
步骤1:IAccountDao接口中给每个方法都添加相应的注解,并写入相应的sql语句。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.dao; 2 3 import fdx.domain.Account; 4 import org.apache.ibatis.annotations.Insert; 5 import org.apache.ibatis.annotations.Select; 6 7 import java.util.List; 8 9 public interface IAccountDao { 10 //查询所有账户 11 @Select("select * from account") 12 public List<Account> findAll(); 13 //保存账户信息 14 @Insert(value="insert into account (name,money) values (#{name},#{money})") 15 public void saveAccount(Account account); 16 17 }
步骤2:在resource中编写核心配置文件SqlMapConfig.xml,连接ssm数据库,提供数据库用户名与密码。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <environments default="mysql"> 7 <environment id="mysql"> 8 <transactionManager type="JDBC"/> 9 <dataSource type="POOLED"> 10 <property name="driver" value="com.mysql.jdbc.Driver"/> 11 <property name="url" value="jdbc:mysql://localhost/ssm"/> 12 <property name="username" value="root"/> 13 <property name="password" value="0322"/> 14 </dataSource> 15 </environment> 16 </environments> 17 <!-- 使用的是注解 --> 18 <mappers> 19 <!-- <mapper class="fdx.dao.AccountDao"/> --> 20 <!-- 该包下所有的dao接口都可以使用 --> 21 <package name="fdx.dao"/> 22 </mappers> 23 </configuration>
步骤3:进行测试。java/fdx/test包中建立一个TestMybatis类,对两种方法进行测试。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.test; 2 import java.io.InputStream; 3 import java.util.List; 4 import org.apache.ibatis.io.Resources; 5 import org.apache.ibatis.session.SqlSession; 6 import org.apache.ibatis.session.SqlSessionFactory; 7 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 8 import org.junit.Test; 9 import fdx.dao.IAccountDao; 10 import fdx.domain.Account; 11 public class TestMyBatis { 12 @Test 13 public void run1() throws Exception { 14 // 加载配置文件 15 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 16 // 创建工厂 17 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); 18 // 创建sqlSession对象 19 SqlSession session = factory.openSession(); 20 // 获取代理对象 21 IAccountDao dao = session.getMapper(IAccountDao.class); 22 // 调用查询的方法 23 List<Account> list = dao.findAll(); 24 for (Account account : list) { 25 System.out.println(account); 26 } 27 // 释放资源 28 session.close(); 29 inputStream.close(); 30 } 31 @Test 32 public void run2() throws Exception { 33 Account account = new Account(); 34 account.setName("熊大"); 35 account.setMoney(400d); 36 // 加载配置文件 37 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 38 // 创建工厂 39 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); 40 // 创建sqlSession对象 41 SqlSession session = factory.openSession(); 42 // 获取代理对象 43 IAccountDao dao = session.getMapper(IAccountDao.class); 44 dao.saveAccount(account); 45 // 提交事务 46 session.commit(); 47 // 释放资源 48 session.close(); 49 inputStream.close(); 50 } 51 }
可以看到我们可以查询数据库表格中的数据,也可以往数据库中添加数据。
Spring整合MyBatis框架
步骤1:配置applicationContext.xml。配置C3P0的连接池对象,配置SqlSession的工厂,配置扫描dao的包。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx.xsd"> 15 <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架 16 去管理 --> 17 <context:component-scan base-package="fdx"> 18 <!-- 配置要忽略的注解 --> 19 <context:exclude-filter type="annotation" 20 expression="org.springframework.stereotype.Controller"/> 21 </context:component-scan> 22 <!-- Spring整合MyBatis --> 23 <!-- 配置C3P0的连接池对象 --> 24 <bean id="dataSource" 25 class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 26 <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 27 <property name="url" value="jdbc:mysql:///ssm" /> 28 <property name="username" value="root" /> 29 <property name="password" value="0322" /> 30 </bean> 31 <!-- 配置SqlSession的工厂 --> 32 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 33 <property name="dataSource" ref="dataSource" /> 34 </bean> 35 <!-- 配置扫描dao的包 --> 36 <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 37 <property name="basePackage" value="fdx.dao"/> 38 </bean> 39 </beans>
步骤2:删除SqlMapConfig.xml配置文件。
步骤3:给IAccountDao加@Repository注解,表示交由Springioc管理。
步骤4:在AccoutServiceImpl中注入dao对象并添加@Autowired注解,调用dao对象的方法进行测试。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.service.impl; 2 3 import fdx.dao.IAccountDao; 4 import fdx.domain.Account; 5 import fdx.service.IAccountService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 9 import java.util.List; 10 //该注解表示把service交给ioc管理 11 @Service("accountService") 12 public class AccountServiceImpl implements IAccountService { 13 @Autowired 14 private IAccountDao accountDao; 15 @Override 16 public List<Account> findAll() { 17 System.out.println("业务层:查询所有账户"); 18 return accountDao.findAll(); 19 } 20 21 @Override 22 public void saveAccount(Account account) { 23 System.out.println("业务层:保存账户"); 24 accountDao.saveAccount(account); 25 26 } 27 }
步骤5:在AccountController中注入service对象并添加@Autowired注解,创建一个Model对象来添加list属性。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.controller; 2 3 import fdx.domain.Account; 4 import fdx.service.IAccountService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 10 import java.util.List; 11 12 @Controller 13 @RequestMapping("/account") 14 public class AccountController { 15 @Autowired 16 private IAccountService accoutService; 17 @RequestMapping("/findAll") 18 public String findAll(Model model) { 19 System.out.println("表现层:查询所有账户"); 20 List <Account> list = accoutService.findAll(); 21 model.addAttribute("list",list); 22 return "list"; 23 } 24 }
步骤6:编辑list页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <html> 4 <head> 5 <title>Title</title> 6 </head> 7 <body> 8 <h3>查询所有账户</h3> 9 <c:forEach items="${list}" var="account"> 10 ${account.name} 11 </c:forEach> 12 </body> 13 </html>
Spring的声明式事务管理
步骤1:配置applicationContext.xml,添加事务管理器与通知
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx.xsd"> 15 <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架 16 去管理 --> 17 <context:component-scan base-package="fdx"> 18 <!-- 配置要忽略的注解 --> 19 <context:exclude-filter type="annotation" 20 expression="org.springframework.stereotype.Controller"/> 21 </context:component-scan> 22 <!-- Spring整合MyBatis --> 23 <!-- 配置C3P0的连接池对象 --> 24 <bean id="dataSource" 25 class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 26 <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 27 <property name="url" value="jdbc:mysql:///ssm" /> 28 <property name="username" value="root" /> 29 <property name="password" value="0322" /> 30 </bean> 31 <!-- 配置SqlSession的工厂 --> 32 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 33 <property name="dataSource" ref="dataSource" /> 34 </bean> 35 <!-- 配置扫描dao的包 --> 36 <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 37 <property name="basePackage" value="fdx.dao"/> 38 </bean> 39 <!--声明式事务管理--> 40 <!--配置事务管理器--> 41 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 42 <property name="dataSource" ref="dataSource"/> 43 </bean> 44 <!--配置事务通知--> 45 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 46 <tx:attributes> 47 <tx:method name="find*" read-only="true"/> 48 <tx:method name="*" isolation="DEFAULT"/> 49 </tx:attributes> 50 </tx:advice> 51 <!--配置aop增强--> 52 <aop:config> 53 <aop:advisor advice-ref="txAdvice" pointcut="execution(* fdx.service.impl.*ServiceImpl.*(..))"/> 54 </aop:config> 55 </beans>
步骤2:编辑index.jsp,添加姓名与money的输入框与一个提交按钮
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <a href="account/findAll">测试</a> 8 <h3>测试包</h3> 9 <form action="account/save" method="post"> 10 姓名:<input type="text" name="name" /><br/> 11 金额:<input type="text" name="money" /><br/> 12 <input type="submit" value="保存" /><br/> 13 </form> 14 </body> 15 </html>
步骤3:在AccountController中添加一个save方法,用service层对象调用saveAccount()方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package fdx.controller; 2 3 import fdx.domain.Account; 4 import fdx.service.IAccountService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 10 import java.util.List; 11 12 @Controller 13 @RequestMapping("/account") 14 public class AccountController { 15 @Autowired 16 private IAccountService accoutService; 17 @RequestMapping("/findAll") 18 public String findAll(Model model) { 19 System.out.println("表现层:查询所有账户"); 20 List <Account> list = accoutService.findAll(); 21 model.addAttribute("list",list); 22 return "list"; 23 } 24 25 @RequestMapping("/save") 26 public String save(Account account) { 27 accoutService.saveAccount(account); 28 return "list"; 29 } 30 }