文章目录
1. SSM 整合说明
- SSM 整合可以使用多种方式,我们会采用 XML + 注解的方式
- 我们使用 Spring 去整合 SpringMVC 和 MyBatis
2. SSM 整合步骤
- 环境搭建
- 搭建 Spring 框架
- 搭建 SpringMVC 框架
- 使用 Spring 整合 SpringMVC
- 搭建 MyBatis 框架
- 使用 Spring 整合 MyBatis
3. 环境搭建
-
搭建数据库环境
create database ssm; use ssm; create table account( id int primary key auto_increment, name varchar(20), money double );
-
创建一个 Maven 工程
-
选择骨架 org.apache.maven.archetypes:maven-archetype-webapp,点击 Next
-
添加 Maven Property(这样可以解决 maven 项目创建过慢的问题),点击 Next
Name:archetypeCatalog Value:internal
-
选择项目本地路径,点击 Finish
-
-
补全 maven 项目目录结构(此时的 maven 项目目录结构还不完整)
- 在 mian 包下创建 java 包,右键 Mark Derictory As --> Sources Root
- 在 mian 包下创建 resources 包,右键 Mark Derictory As --> Resources Root
-
导入坐标依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zt</groupId> <artifactId>springmvc_day03</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc_day03 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> <build> <finalName>springmvc_day03</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
-
导入 log4j 配置文件到 resources 中
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=info, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
-
编写 domain 层
Account
public class Account implements Serializable { private Integer id; private String name; private double money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
-
编写 dao 层
AccountDao 接口
public interface AccountDao { List<Account> findAll(); void saveAccount(Account account); }
-
编写 service 层
AccountService 接口
public interface AccountService { List<Account> findAll(); void saveAccount(Account account); }
AccountServiceImpl
public class AccountServiceImpl implements AccountService { @Override public List<Account> findAll() { System.out.println("查询所有账户"); return null; } @Override public void saveAccount(Account account) { System.out.println("保存账户"); } }
-
创建 controller 层
AccountController
@Controller @RequestMapping("/account") public class AccountController { @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层:查询所有账户"); return "list"; } }
4. 搭建 Spring 框架
-
在 resources 中编写 applicationContext.xml 的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--开启注解扫描,要扫描的是 service 和 dao 层的注解,要忽略 web 层注解, 因为 web 层要让 SpringMVC 框架去管理--> <context:component-scan base-package="com.zt"> <!--配置不需要扫描的 Controller 注解--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> </context:component-scan> </beans>
-
在 AccountServiceImpl 中加入 @Service(“accountService”)
@Service("accountService") public class AccountServiceImpl implements AccountService { @Override public List<Account> findAll() { System.out.println("查询所有账户"); return null; } @Override public void saveAccount(Account account) { System.out.println("保存账户"); } }
-
创建测试类,测试 Spring 能否独立运行
public class AccountServiceTest { @Test public void testFindAll(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = applicationContext.getBean("accountService", AccountService.class); accountService.findAll(); } }
5. 搭建 SpringMVC 框架
-
在 web.xml 中配置前端控制器和过滤器(解决 post 请求参数中文乱码问题)
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!--配置前端控制器--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置 servlet 的初始化参数,读取 springmvc 的配置文件,创建 spring 容器 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 配置 servlet 启动时加载对象 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置过滤器解决 post 请求参数中文乱码问题--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
-
在 resources 中创建 springmvc.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置spring创建容器时要扫描的包 --> <context:component-scan base-package="com.zt"> <!--配置要扫描的 Controller 注解,其他注解不扫描--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter> </context:component-scan> <!-- 配置视图解析器 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 设置静态资源不过滤 --> <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 --> <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 --> <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript --> <!-- 配置spring开启注解mvc的支持--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
-
编写 index.jsp 和 list.jsp
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="account/findAll">findAll</a> </body> </html>
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h3>执行了findAll</h3> </body> </html>
-
配置 tomcat 服务器,启动项目,在浏览器中进行测试
6. 使用 Spring 整合 SpringMVC
-
整合目的
在 controller 中能通过依赖注入创建 service 对象
-
整合思路
要通过依赖注入创建对象,首先要加载 Spring 的配置文件。我们不应该再去手动加载 Spring 的配置文件,因为每次要获取对象,就会去读取一次配置文件,会降低程序的效率。应该在服务器启动时,就加载 Spring 的配置文件,并且只加载一次,这样会提高程序的效率。
Spring 已经为我们提供了监听器 ContextLoaderListener,可监听 ServletContext 对象的创建,我们知道 ServletContext 对象是随着服务器的启动而创建的,并且只创建一次,因此我们可以让监听器 ContextLoaderListener 去加载Spring 的配置文件。
-
实现
-
在web.xml中配置 ContextLoaderListener 监听器
<!--配置 Spring 的监听器,默认只加载 WEB-INF 目录下的 applicationContext.xml 配置文件--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--设置配置文件的路径--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
-
在 controller 中注入 service 对象
@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层:查询所有账户"); accountService.findAll(); return "list"; } }
-
启动项目,在浏览器中进行测试
-
7. 搭建 MyBatis 框架
-
在 AccountDao 接口的方法上添加注解,编写 SQL 语句
public interface AccountDao { @Select("select * from account") List<Account> findAll(); @Insert("insert into account(name,money) values(#{name},#{money})") void saveAccount(Account account); }
-
在 resources 中编写 SqlMapConfig.xml 的配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置 mybatis 的环境 --> <environments default="mysql"> <!-- 配置 mysql 的环境 --> <environment id="mysql"> <!-- 配置事务的类型 --> <transactionManager type="JDBC"></transactionManager> <!-- 配置连接数据库的信息:用的是数据源(连接池) --> <dataSource type="POOLED"> <!--配置连接数据库的四个基本信息--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!-- 告知 mybatis 映射配置的位置 --> <mappers> <package name="com.zt.dao"></package> </mappers> </configuration>
-
编写测试方法
public class AccountDaoTest { private InputStream in; private SqlSession sqlSession; private AccountDao mapper; @Before public void init() throws IOException { // 1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 2.创建 SqlSessionFactory 的构建者对象 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); // 3.使用构建者创建工厂对象 SqlSessionFactory SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in); // 4.使用 SqlSessionFactory 生产 SqlSession 对象 sqlSession = sqlSessionFactory.openSession(); // 5.使用 SqlSession 创建 dao 接口的代理对象 mapper = sqlSession.getMapper(AccountDao.class); } @After public void destory() throws IOException { // 注意 mybatis 默认是手动提交 sqlSession.commit(); // 7.释放资源 sqlSession.close(); in.close(); } @Test public void testFindAll(){ List<Account> accounts = mapper.findAll(); for (Account account : accounts) { System.out.println(account); } } @Test public void testSaveAccount(){ Account account = new Account(); account.setName("张三"); account.setMoney(3000); mapper.saveAccount(account); } }
8. 使用 Spring 整合 MyBatis
-
整合目的
在 service 中能通过依赖注入创建 dao 对象
-
整合思路
我们单独使用 MyBatis 时,是使用代理 Dao 的方式实现 CRUD 的。现在要通过依赖注入创建 dao 对象,就是把代理 Dao 交给 Spring 的 IOC 容器去管理,也就是把 SqlMapConfifig.xml 配置文件中的内容配置到 applicationContext.xml 配置文件中。
-
实现
-
在 applicationContext.xml 中配置 Spring 整合 MyBatis
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--开启注解扫描,要扫描的是 service 和 dao 层的注解,要忽略 web 层注解, 因为 web 层要让 SpringMVC 框架去管理--> <context:component-scan base-package="com.zt"> <!--配置不需要扫描的 Controller 注解--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> </context:component-scan> <!--Spring整合MyBatis框架--> <!--配置连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"/> <property name="user" value="root"/> <property name="password" value="123456"/> </bean> <!--配置 SqlSessionFactory 工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置 AccountDao 接口所在包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zt.dao"/> </bean> <!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!--配置AOP增强--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zt.service.impl.*ServiceImpl.*(..))"/> </aop:config> </beans>
-
删除 SqlMapConfifig.xml 配置文件
-
在 AccountDao 接口中添加 @Repository 注解
@Repository public interface AccountDao { @Select("select * from account") List<Account> findAll(); @Insert("insert into account(name,money) values(#{name},#{money})") void saveAccount(Account account); }
-
在 service 中注入 dao 对象
@Service("accountService") public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { System.out.println("查询所有账户"); List<Account> accounts = accountDao.findAll(); return accounts; } @Override public void saveAccount(Account account) { System.out.println("保存账户"); accountDao.saveAccount(account); } }
-
修改 controller
@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping("/findAll") public ModelAndView findAll(){ ModelAndView modelAndView = new ModelAndView(); System.out.println("表现层:查询所有账户"); List<Account> accounts = accountService.findAll(); modelAndView.addObject("accounts",accounts); modelAndView.setViewName("list"); return modelAndView; } @RequestMapping("/saveAccount") public String saveAccount(Account account){ System.out.println("表现层:保存账户"); accountService.saveAccount(account); return "success"; } }
-
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h3>执行了findAll</h3> ${accounts} </body> </html>
-
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h3>执行了saveAccount</h3> </body> </html>
-
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="account/findAll">findAll</a><br> <form action="account/saveAccount" method="post"> name:<input type="text" name="name"><br> money:<input type="text" name="money"><br> <input type="submit" value="提交"> </form> </body> </html>
-
启动项目,在浏览器中进行测试
-