一、搭建整合环境

1.1 整合思路

  1. 搭建整合环境
  2. 配置spring
  3. spring 整合 springmvc
  4. spring 整合 mybatis

项目截图

1.2 创建数据库

create table account(
    id int primary key auto_increment,
    name varchar(20),
    money double
);

1.3 创建项目

创建maven项目,选择骨架 org.apache.maven.archetypes:maven-archetype-webapp

建立对应的 javaresoucres 目录

1.4 导入依赖

pom.xml

<?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>org.example</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm 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.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.6</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0-alpha-1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.12</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.23</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>ssm</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>

1.5 编写实体类Account

package cn.yijumao.domain;

import org.springframework.stereotype.Component;

/**
 * @author konley
 * @date 2020-09-17 11:33
 * 账户的实体类
 */

@Component
public class Account {
    private Integer id;
    private String name;
    private Double money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + 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;
    }
}

1.6 编写持久层

AccountDao接口

因为使用了mybatis,所以不用编写实现类

package cn.yijumao.dao;

import cn.yijumao.domain.Account;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author konley
 * @date 2020-09-17 11:34
 * 账户dao接口
 */
@Repository
public interface AccountDao {
    /**
     * description: 查询所有账户方法
     * @param
     * @return java.util.List<cn._1jumao.domain.Account>
     */
    @Select("select * from account")
    public List<Account> findAll();

    /**
     * description: 保存账户方法
     * @param account
     * @return void
     */
    @Select("insert into account (name,money) values (#{name},#{money})")
    public void save(Account account);
}

1.7 编写业务层接口及其实现类

UserService接口

package cn.yijumao.service;

import cn.yijumao.domain.Account;

import java.util.List;

/**
 * @author konley
 * @date 2020-09-17 11:36
 */
public interface AccountService {
    /**
     * description: 查询所有账户方法
     * @param
     * @return java.util.List<cn._1jumao.domain.Account>
     */
    public List<Account> findAll();

    /**
     * description: 保存账户方法
     * @param account
     * @return void
     */
    public void save(Account account);
}

UserServiceImpl 实现类

package cn.yijumao.service.impl;

import cn.yijumao.dao.AccountDao;
import cn.yijumao.domain.Account;
import cn.yijumao.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author konley
 * @date 2020-09-17 11:36
 */

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll() {
        System.out.println("业务层:findAll方法");
        return accountDao.findAll();
    }

    @Override
    public void save(Account account) {
        System.out.println("业务层:save方法");
        accountDao.save(account);
    }
}

1.8 编写控制层

AccountController

package cn.yijumao.controller;

import cn.yijumao.dao.AccountDao;
import cn.yijumao.domain.Account;
import cn.yijumao.service.AccountService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author konley
 * @date 2020-09-17 11:37
 * 账户controller
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("表示层:findAll请求");
        //调用service方法
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);
        return "list";
    }

    @RequestMapping("/save")
    public void save(Account account, HttpServletRequest request ,HttpServletResponse response) throws IOException {
        accountService.save(account);
        response.sendRedirect(request.getContextPath()+"/account/findAll");
    }
}

1.8 编写log4j配置文件

log4j.properties

# 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:\\code\\log\\JavaLog
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

二、整合Mybatis和SpringMvc

2.1 编写web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

  <!--1.配置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>

  <!--2.配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载spring mvc的配置文件-->
    <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>

  <!--3.解决中文乱码的过滤器-->
  <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>

2.2 编写Spring配置文件

applicationContext.xml,放在resources下,可以先测试亿下再写完整的

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


<!--开启扫描,排除controller-->
    <context:component-scan base-package="cn.yijumao.service,cn.yijumao.dao,cn.yijumao.domain"/>

    <!--spring整合mybatis
        相当于将mybatis的SqlMapConfig配置文件中的东西转成spring的配置文件
    -->
    <!--0.导入数据库配置文件-->
    <context:property-placeholder location="classpath:druid.properties" ignore-unresolvable="true" system-properties-mode="NEVER"/>
    <!--1.配置连接池-->
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>

    <!--2.配置SqlSessionFactory工厂对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--3.配置AccountDao接口所在的包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.yijumao.dao"/>
    </bean>

    <!--配置spring框架的声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <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(* cn.yijumao.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
</beans>

2.3 编写连接池配置文件

druid.properties

#mysql驱动
driverClassName=com.mysql.jdbc.Driver
#连接地址
url=jdbc:mysql://localhost:3306/ssm_test?useUnicode=true&characterEncoding=utf-8
#用户名
username=root
#密码
password=123456
filters=stat
#  最大并发连接数
maxActive=20
#初始化连接数量
initialSize=1
#超时等待时间以毫秒为单位
maxWait=60000
#最小空闲连接
minIdle=1
#校验连接池中限制时间超过minEvictableIdleTimeMillis的连接对象
timeBetweenEvictionRunsMillis=3000
#连接在池中保持空闲而不被空闲连接回收器线程(如果有)回收的最小时间值,单位毫秒
minEvictableIdleTimeMillis=300000
#SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前
validationQuery=SELECT now();
#指明连接是否被空闲连接回收器(如果有)进行检验.
#如果检测失败,则连接将被从池中去除.
testWhileIdle=true
#指明是否在从池中取出连接前进行检验,如果检验失败,
#则从池中去除连接并尝试取出另一个.
testOnBorrow=false
#指明是否在归还到池中前进行检验
testOnReturn=false
#poolPreparedStatements=true
maxPoolPreparedStatementPerConnectionSize=20

2.4 编写Spring MVC配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!--注解扫描,只扫描controller-->
    <context:component-scan base-package="cn.yijumao.controller"/>

    <!--配置视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--过滤静态资源-->
    <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>

    <!--开启spring mvc的注解支持-->
    <mvc:annotation-driven/>
</beans>

三、编写测试页面

3.1 编写index.jsp

<%--
  Created by IntelliJ IDEA.
  User: konley
  Date: 2020/9/17
  Time: 23:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="account/findAll">findAll测试</a>
    <h3>测试包</h3>
    <form action="account/save" method="post">
        姓名:<input type="text" name="name"/>
        <br>
        金额:<input type="text" name="money">
        <br>
        <input type="submit" value="保存">

    </form>
</body>
</html>

3.2 编写 pages/list.jsp

<%--
  Created by IntelliJ IDEA.
  User: konley
  Date: 2020/9/17
  Time: 23:21
  To change this template use File | Settings | File Templates.
--%>
<%@ 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>查询成功</title>
</head>
<body>
    <h3 style="text-align: center">查询成功</h3>
    <br>
    <table>
        <thead>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>金额</th>
        </tr>
        </thead>
        <tbody>
            <c:forEach items="${list}" var="account">
                <tr>
                    <td>${account.id}</td>
                    <td>${account.name}</td>
                    <td>${account.money}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>

</body>
</html>