SSM整合、Spring整合SpringMVC和Mybatis、事务管理 XML+注解方式 (图文教学,超简单教程)


教程完成代码:ssmTest-GitHub


1. 前言

在前面我们已经学习了Mybatis 、Spring 、 SpringMVC 三个框架,但是在应用中我们一般都是将三个框架一起使用,这一章我们就将这三个框架整合起来。SSM整合可以使用多种方式,咱们会选择XML + 注解的方式。SSM中领头的是Spring,使用Spring来整合Mybatis 和 SpringMVC 框架。

1.1 整合思路

  1. 创建好环境,导入需要用到的jar包
  2. 先搭建Spring框架
  3. 使用Spring整合SpringMVC
  4. 使用Spring整合Mybatis

2. 创建环境

  1. 创建本章节需要用到的数据库及表
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);
  1. 创建maven工程,骨架为webapp,导入坐标
  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <spring.version>5.0.2.RELEASEspring.version>
    <slf4j.version>1.6.6slf4j.version>
    <log4j.version>1.2.12log4j.version>
    <mysql.version>5.1.6mysql.version>
    <mybatis.version>3.4.5mybatis.version>
  properties>

  <dependencies>
    
    <dependency>
      <groupId>org.aspectjgroupId>
      <artifactId>aspectjweaverartifactId>
      <version>1.6.8version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
      <scope>compilescope>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>servlet-apiartifactId>
      <version>2.5version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.0version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>${log4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.0version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>
  dependencies>
  1. 创建java和resources文件夹
    SSM整合、Spring整合SpringMVC和Mybatis、事务管理 XML+注解方式 (图文教学,超简单教程)_第1张图片

3. Spring

3.1 Spring 配置文件

在resources文件夹中创建ApplicationContext.xml配置文件


<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">

    
    <context:component-scan base-package="com.lois">
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
beans>

3.2 测试Spring

  1. 创建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方法执行了");
    }
}
  1. 编写测试类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();
    }
}
  1. 运行测试类中的方法
    在这里插入图片描述

3. SpringMVC

3.1 搭建SpringMVC

跟以前单独搭建SpringMVC一样

  1. 修改ssmtest\src\main\webapp\WEB-INF\web.xml 文件,添加 前端控制器 和 过滤器解决中文乱码
  
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  <filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
    
    <init-param>
      <param-name>forceEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  1. 在resources文件夹中创建配置文件springmvc.xml

<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">

    
    <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>

    
    <mvc:annotation-driven/>

    
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>

beans>

3.2 测试SpringMVC

  1. 创建com.lois.controller.AccountController 类,编写测试方法
@Controller
@RequestMapping("/account")
public class AccountController  {
    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("AccountController中findAll方法执行了");
        return "success";
    }
}
  1. 修改wabapp/index.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <a href="/account/findAll">测试SpringMVCa>
body>
html>

  1. 创建 webapp\WEB-INF\pages\success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>successtitle>
head>
<body>
    测试成功
body>
html>
  1. 运行服务器,测试链接
    页面成功调整,控制台输出,证明我们搭建成功
    在这里插入图片描述

3.3 Spring整合SpringMVC的框架

我们配置好了SpringMVC,但是有一个问题,就是在controller中不能调用service和dao层,这是为什么呢?在我们启动Tomcat的时候,服务器会加载webapp\WEB-INF\web.xml ,在web.xml 我们配置了前端控制器去加载springmvc.xml文件,但是没有加载ApplicationContext.xml文件,所以Spring的没有启动。

目的:在controller中能成功的调用service对象中的方法。

  1. 在ssmtest\src\main\webapp\WEB-INF\web.xml 中 添加 监听器, 在项目启动的时候,就去加载applicationContext.xml的配置文件(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件,所以我们需要手动设置加载路径)
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:ApplicationContext.xmlparam-value>
  context-param>
  1. 以下是测试 ,创建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();
    }
}
  1. 修改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";
    }
}
  1. 重启服务器,再次测试链接
    在这里插入图片描述

4. Mybatis

Mybatis不是Spring家的,但是Spring对Mybatis做了一个整合,在我们项目管理里pom中,我们导入了

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.0version>
    dependency>

这个就是Spring对Mybatis的整合。
我们这里就直接使用ApplicationContext.xml来对Mybatis进行配置

4.1 Spring整合Mybatis

  1. 在ApplicationContext.xml配置文件中添加Mybatis的配置
    
    
    <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>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lois.dao"/>
    bean>

    
  1. 创建com.lois.domain.Account实体类,生成set/get/toString方法
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Integer money;
}
  1. 因为我们使用了Mybatis,所以不用自己写实现类了,删除com.lois.dao.impl.AccountDaoImpl.java实现类,修改com.lois.dao.AccountDao接口类
@Repository
public interface AccountDao {

    @Select("select * from account")
    public List<Account> findAll();
}
  1. 修改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();
    }
}
  1. 修改 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;
    }
}
  1. 修改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>successtitle>
head>
<body>
    测试成功<br>

    <c:forEach items="${Account}" var="account" >
        ${account.toString()}<br>
    c:forEach>
body>
html>
  1. 运行服务器,查看结果
    SSM整合、Spring整合SpringMVC和Mybatis、事务管理 XML+注解方式 (图文教学,超简单教程)_第2张图片

4.2 配置Spring的事务

4.2.1 配置

  1. 在ApplicationContext.xml配置文件中,添加配置
    

    
    <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:config>
        
        <aop:pointcut id="pt1" expression="execution(* com.lois.service.impl.*.*(..))"/>
        
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    aop:config>
    
    

4.2.2 测试

  1. 修改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>
  1. 向com.lois.controller.AccountController中添加方法
    @RequestMapping("/save")
    public String save(Account account){
        accountService.save(account);
        return "success";
    }
  1. 向com.lois.service.AccountService接口类和com.lois.service.impl.AccountServiceImpl实现类添加方法
void save(Account account);
@Override
public void save(Account account) {
    accountDao.save(account);
}
  1. 向com.lois.dao.AccountDao接口类中添加方法
@Insert("insert into account(`name`,`money`) values (#{name},#{money})")
void save(Account account);
  1. 启动服务器,填写表单测试
    在这里插入图片描述
    在这里插入图片描述
    测试成功

你可能感兴趣的:(java)