教程完成代码:ssmTest-GitHub
1. 前言
在前面我们已经学习了Mybatis 、Spring 、 SpringMVC 三个框架,但是在应用中我们一般都是将三个框架一起使用,这一章我们就将这三个框架整合起来。SSM整合可以使用多种方式,咱们会选择XML + 注解的方式。SSM中领头的是Spring,使用Spring来整合Mybatis 和 SpringMVC 框架。
1.1 整合思路
- 创建好环境,导入需要用到的jar包
- 先搭建Spring框架
- 使用Spring整合SpringMVC
- 使用Spring整合Mybatis
2. 创建环境
- 创建本章节需要用到的数据库及表
create database ssmtest;
use ssmtest;
drop table if exists `account`;
create table `account`(
`id` int(10) primary key auto_increment,
`name` varchar(20),
`money` int
);
insert into `account`(`name`,`money`) values ('小明',1000),('小红',1000);
- 创建maven工程,骨架为webapp,导入坐标
<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>
<!-- spring -->
<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>
<!-- log start -->
<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>
<!-- log end -->
<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>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
- 创建java和resources文件夹
3. Spring
3.1 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.lois">
<!-- 配置要忽略的注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
3.2 测试Spring
- 创建com.lois.dao.AccountDao接口类和com.lois.dao.impl.AccountDaoImpl实现类
public interface AccountDao {
public void findAll();
}
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Override
public void findAll() {
System.out.println("AccountDaoImpl的findAll方法执行了");
}
}
- 编写测试类com.lois.client.AccountClient(此类在java包中,不是在test包中)
public class AccountClient {
@Test
public void findAll(){
ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
AccountDao accountDao = ac.getBean("accountDao", AccountDao.class);
accountDao.findAll();
}
}
- 运行测试类中的方法
3. SpringMVC
3.1 搭建SpringMVC
跟以前单独搭建SpringMVC一样
- 修改ssmtest\src\main\webapp\WEB-INF\web.xml 文件,添加 前端控制器 和 过滤器解决中文乱码
<!-- SpringMVC的核心控制器 -->
<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>
<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>
<!-- 启动过滤器 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- 过滤所有请求 但是静态资源我们不需要拦截,如图片、css、js等,我们需要在spring的配置文件中写明-->
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 在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">
<!-- 扫描controller的注解,别的不扫描 -->
<context:component-scan base-package="com.lois">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--视图存放的位置-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--视图的后缀名-->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置spring开启注解mvc的支持-->
<mvc:annotation-driven/>
<!-- location 表示路径,mapping 表示文件,**表示该目录下的文件以及子目录的文件 -->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
</beans>
3.2 测试SpringMVC
- 创建com.lois.controller.AccountController 类,编写测试方法
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("AccountController中findAll方法执行了");
return "success";
}
}
- 修改wabapp/index.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/account/findAll">测试SpringMVC</a>
</body>
</html>
- 创建 webapp\WEB-INF\pages\success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
测试成功
</body>
</html>
- 运行服务器,测试链接
页面成功调整,控制台输出,证明我们搭建成功
3.3 Spring整合SpringMVC的框架
我们配置好了SpringMVC,但是有一个问题,就是在controller中不能调用service和dao层,这是为什么呢?在我们启动Tomcat的时候,服务器会加载webapp\WEB-INF\web.xml ,在web.xml 我们配置了前端控制器去加载springmvc.xml文件,但是没有加载ApplicationContext.xml文件,所以Spring的没有启动。
目的:在controller中能成功的调用service对象中的方法。
- 在ssmtest\src\main\webapp\WEB-INF\web.xml 中 添加 监听器, 在项目启动的时候,就去加载applicationContext.xml的配置文件(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件,所以我们需要手动设置加载路径)
<!--配置Spring的监听器-->
<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>
- 以下是测试 ,创建com.lois.service.AccountService接口类和com.lois.service.impl.AccountServiceImpl实现类
public interface AccountService {
public void findAll();
}
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void findAll() {
System.out.println("AccountServiceImpl的findAll方法执行了");
accountDao.findAll();
}
}
- 修改AccountController 类, 注入AccountService
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(){
System.out.println("AccountController中findAll方法执行了");
accountService.findAll();
return "success";
}
}
- 重启服务器,再次测试链接
4. Mybatis
Mybatis不是Spring家的,但是Spring对Mybatis做了一个整合,在我们项目管理里pom中,我们导入了
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
这个就是Spring对Mybatis的整合。
我们这里就直接使用ApplicationContext.xml来对Mybatis进行配置
4.1 Spring整合Mybatis
- 在ApplicationContext.xml配置文件中添加Mybatis的配置
<!-- Mybatis-start -->
<!-- 配置连接池对象 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///ssmtest"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置SqlSession的工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置扫描dao的包(相当于mappers) -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lois.dao"/>
</bean>
<!-- Mybatis-end -->
- 创建com.lois.domain.Account实体类,生成set/get/toString方法
public class Account implements Serializable {
private Integer id;
private String name;
private Integer money;
}
- 因为我们使用了Mybatis,所以不用自己写实现类了,删除com.lois.dao.impl.AccountDaoImpl.java实现类,修改com.lois.dao.AccountDao接口类
@Repository
public interface AccountDao {
@Select("select * from account")
public List<Account> findAll();
}
- 修改com.lois.service.AccountService接口类和com.lois.service.impl.AccountServiceImpl实现类
public interface AccountService {
public List<Account> findAll();
}
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("AccountServiceImpl的findAll方法执行了");
return accountDao.findAll();
}
}
- 修改 com.lois.controller.AccountController 类
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public ModelAndView findAll(ModelAndView mv){
System.out.println("AccountController中findAll方法执行了");
mv.addObject("Account",accountService.findAll());
mv.setViewName("success");
return mv;
}
}
- 修改success.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>success</title>
</head>
<body>
测试成功<br>
<c:forEach items="${Account}" var="account" >
${account.toString()}<br>
</c:forEach>
</body>
</html>
- 运行服务器,查看结果
4.2 配置Spring的事务
4.2.1 配置
- 在ApplicationContext.xml配置文件中,添加配置
<!-- Spring事务管理-start -->
<!--配置事务管理器-->
<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" propagation="SUPPORTS"/>
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置AOP-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.lois.service.impl.*.*(..))"/>
<!-- 建立通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
<!-- Spring事务管理-end -->
4.2.2 测试
- 修改index.jsp,添加表单
<form action="/account/save" method="post">
账户名:<input type="text" name="name"><br>
金额:<input type="text" name="money"><br>
<input type="submit" value="提交">
</form>
- 向com.lois.controller.AccountController中添加方法
@RequestMapping("/save")
public String save(Account account){
accountService.save(account);
return "success";
}
- 向com.lois.service.AccountService接口类和com.lois.service.impl.AccountServiceImpl实现类添加方法
void save(Account account);
@Override
public void save(Account account) {
accountDao.save(account);
}
- 向com.lois.dao.AccountDao接口类中添加方法
@Insert("insert into account(`name`,`money`) values (#{name},#{money})")
void save(Account account);
- 启动服务器,填写表单测试
测试成功