1. 搭建整合环境

  • 采用 XML+ 注解的方式进行整合
  • 整合思路:
    • 先搭建整合环境
    • 再把 Spring 配置搭建完成
    • 再使用 Spring 整合 SpringMVC 框架
    • 最后使用 Spring 整合 MyBatis 框架
  • 创建数据库和表结构
    create database ssm;
    use ssm;
    create table account(
        id int primary key auto_increment,
        name varchar(20),
        money double
    );
    
  • Maven 坐标
    <?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>pers.ylq</groupId>
      <artifactId>ssm_first</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <name>ssm_first 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>
        <!-- JDK8   -->
        <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>
        <!-- Spring-aop   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- Spring核心容器   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- SpringMVC   -->
        <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>
        <!-- Spring整合Junit   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- Spring事务管理   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- Spring JDBCTemplate   -->
        <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>test</scope>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
        </dependency>
        <!-- Servlet   -->
        <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>
        <!-- mybatis   -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
        </dependency>
        <!-- Spring整合mybatis   -->
        <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>
        <!-- 日志开始   -->
        <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>
      </dependencies>
      <!-- 日志结束   -->
      <build>
        <finalName>ssm_first</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>
            <!-- tomcat7 -->
            <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.2</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>
    
  • 编写实体类,在 domain 包中
    package pers.ylq.domain;
    
    import java.io.Serializable;
    
    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 层接口
    package pers.ylq.dao;
    
    import pers.ylq.domain.Account;
    
    import java.util.List;
    
    public interface AccountDao {
        public void saveAccount(Account account);
    
        public List<Account> findAll();
    }
    
  • 编写 service 接口
    package pers.ylq.service;
    
    import pers.ylq.domain.Account;
    
    import java.util.List;
    
    public interface AccountService {
        void saveAccount(Account account);
    
        List<Account> findAll();
    }
    
  • 编写 service 实现类
    package pers.ylq.service.impl;
    
    import org.springframework.stereotype.Service;
    import pers.ylq.dao.AccountDao;
    import pers.ylq.domain.Account;
    import pers.ylq.service.AccountService;
    
    import java.util.List;
    
    @Service("accountService")
    public class AccountServiceImpl implements AccountService {
    
        private AccountDao accountDao;
    
        @Override
        public void saveAccount(Account account) {
            System.out.println("业务层:保存账号...");
        }
    
        @Override
        public List<Account> findAll() {
            System.out.println("业务层:查询所有账号...");
            return null;
        }
    }
    

2. Spring 框架代码的编写

  • 搭建 Spring 开发环境

    <?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="pers.ylq">
            <!-- 配置要忽略的注解 -->
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    </beans>
    
    • Spring 和 SpringMVC 配置文件都会去扫描包。
    • Spring 通过容器对象 ClassPathXmlApplicationContext 加载配置文件,SpringMVC 在 web.xml 中配置前端控制器的时候加载 springmvc.xml 配置文件。
    • 那么会有两个容器,Spring 的是父容器,springmvc 的是子容器。
    • 我们需要让 SpringMVC 只扫描 Controller,让 Spring 扫描全部包,但排除 Controller
  • 编写测试类进行测试

    package pers.ylq.test;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import pers.ylq.service.AccountService;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:applicationContext.xml")
    public class TestSpring {
        @Autowired
        private AccountService accountService;
    
        @Test
        public void run1(){
            accountService.findAll();
        }
    }
    

3. SpringMVC 环境搭建

  • 在 web.xml 中配置 DispatcherServlet 前端控制器和中文乱码过滤器

    <!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>
    
        <!-- 配置解决中文乱码的过滤器 -->
        <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>
    
        <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 -->
        <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    
  • 创建 springmvc.xm l 的配置文件,编写配置文件

    <?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="pers.ylq">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!-- 配置视图解析器 -->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- JSP文件所在的目录 -->
            <property name="prefix" value="/WEB-INF/pages/"/>
            <!-- 文件的后缀名 -->
            <property name="suffix" value=".jsp"/>
        </bean>
    
        <!-- 设置静态资源不过滤 -->
        <mvc:resources location="/css/" mapping="/css/**"/>
        <mvc:resources location="/images/" mapping="/images/**"/>
        <mvc:resources location="/js/" mapping="/js/**"/>
    
    
        <!-- 开启对SpringMVC注解的支持 -->
        <mvc:annotation-driven/>
    
    </beans>
    
  • 测试 SpringMVC 的框架搭建是否成功

    • 编写 index.jsp 和 list.jsp 编写,超链接
    <a href="account/findAll">查询所有</a>
    
    • 创建 AccountController 类,编写方法,进行访问测试
      package pers.ylq.controller;
      
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;
      
      @Controller
      @RequestMapping("/account")
      public class AccountController {
          @RequestMapping("/findAll")
          public String findAll(){
              System.out.println("表现层:查询所有账户...");
              return "list";
          }
      }
      

4. Spring 整合 SpringMVC 框架

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

  • 原理:

    • 配置一个监听器,监听 ServletContext 域对象的创建,在监听器中加载配置文件,创建工厂,存储到 ServletContext 域中。
    • Spring 已经帮我们创建好了这个监听器(ContextLoaderListener),我们加载即可。
  • 在 web.xml 中配置 ContextLoaderListener 监听器

    <!-- 配置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>
    
    • 该监听器只能加载 WEB-INF 目录下的 applicationContext.xml 的配置文件,配置文件放置在 resources 目录下,我们需要手动配置加载路径。
  • 在 controller 中注入 service 对象,调用 service 对象的方法进行测试

    package pers.ylq.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import pers.ylq.service.AccountService;
    
    @Controller
    @RequestMapping("/account")
    public class AccountController {
        @Autowired
        private AccountService accountService;
    
        @RequestMapping("/findAll")
        public String findAll() {
            System.out.println("表现层:查询所有账户...");
            accountService.findAll();
            return "list";
        }
    }
    
  • 测试跳转。

5. MyBatis 环境搭建

  • 编写数据库配置文件 jdbcConfig.properties
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm
    jdbc.username=root
    jdbc.password=123456
    
  • 在 Web 项目中编写 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>
    
        <!-- 引入类路径下的数据库配置文件   -->
        <properties resource="jdbcConfig.properties"/>
    
        <!-- 给domain中的包起别名   -->
        <typeAliases>
            <package name="pers.ylq.domain"/>
        </typeAliases>
        <!--  配置数据库     -->
        <environments default="mysql">
            <environment id="mysql">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="${jdbc.driver}"/>
                    <property name="url" value="${jdbc.url}"/>
                    <property name="username" value="${jdbc.username}"/>
                    <property name="password" value="${jdbc.password}"/>
                </dataSource>
            </environment>
        </environments>
    
        <!-- 映射文件   -->
        <mappers>
            <package name="pers.ylq.dao"/>
        </mappers>
    </configuration>
    
  • 在 AccountDao 接口的方法上添加注解,编写 SQL 语句
    package pers.ylq.dao;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    import pers.ylq.domain.Account;
    
    import java.util.List;
    
    public interface AccountDao {
        @Insert("insert into account(name,money) values(#{name},#{money})")
        public void saveAccount(Account account);
    
        @Select("select * from account")
        public List<Account> findAll();
    }
    
  • 编写测试方法
    package pers.ylq.test;
    
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    import pers.ylq.dao.AccountDao;
    import pers.ylq.domain.Account;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class TestMyBatis {
        @Test
        public void run1() throws IOException {
            // 加载配置文件
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            // 创建工厂
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            // 创建sqlSession对象,并设置自动提交
            SqlSession sqlSession = factory.openSession(true);
            // 获取代理对象
            AccountDao dao = sqlSession.getMapper(AccountDao.class);
            // 调用查询的方法
            List<Account> list = dao.findAll();
            for (Account account : list) {
                System.out.println(account);
            }
            // 释放资源
            sqlSession.close();
            inputStream.close();
        }
    
        @Test
        public void run2() throws Exception {
            Account account = new Account();
            account.setName("熊大");
            account.setMoney(400d);
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = factory.openSession();
            AccountDao dao = sqlSession.getMapper(AccountDao.class);
            dao.saveAccount(account);
            sqlSession.commit();
            sqlSession.close();
            inputStream.close();
        }
    }
    

6. Spring 整合 MyBatis 框架

  • 目的:把 SqlMapConfig.xml 配置文件中的内容配置到 applicationContext.xml 配置文件中。
    
    <!-- Spring整合MyBatis   -->
    <!-- 读取数据库配置文件 -->
    <context:property-placeholder location="classpath:jdbcConfig.properties"/>
    <!-- 配置C3P0的连接池对象 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <!-- 配置SqlSession的工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置 下划线转驼峰式 -->
        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="mapUnderscoreToCamelCase" value="true"/>
            </bean>
        </property>
    </bean>
    
    <!-- 配置扫描dao的包 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="pers.ylq.dao"/>
    </bean>
    
  • 在 AccountDao 接口中添加 @Repository 注解
  • 在 service 中注入 dao 对象,进行测试
    package pers.ylq.service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import pers.ylq.dao.AccountDao;
    import pers.ylq.domain.Account;
    import pers.ylq.service.AccountService;
    
    import java.util.List;
    
    @Service("accountService")
    public class AccountServiceImpl implements AccountService {
    
        @Autowired
        private AccountDao accountDao;
    
        @Override
        public void saveAccount(Account account) {
            System.out.println("业务层:保存账号...");
        }
    
        @Override
        public List<Account> findAll() {
            System.out.println("业务层:查询所有账号...");
            return accountDao.findAll();
        }
    }
    

7. 配置 Spring 的声明式事务管理

  • <!-- 配置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*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 配置AOP增强  -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* pers.ylq.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
    
  • 测试保存

8. 完整代码

  • 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>pers.ylq</groupId>
      <artifactId>ssm_first</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <name>ssm_first 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>
        <!-- JDK8   -->
        <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>
        <!-- Spring-aop   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- Spring核心容器   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- SpringMVC   -->
        <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>
        <!-- Spring整合Junit   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- Spring事务管理   -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <!-- Spring JDBCTemplate   -->
        <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>test</scope>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
        </dependency>
        <!-- Servlet   -->
        <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>
        <!-- mybatis   -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
        </dependency>
        <!-- Spring整合mybatis   -->
        <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>
        <!-- 日志开始   -->
        <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>
      </dependencies>
      <!-- 日志结束   -->
      <build>
        <finalName>ssm_first</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>
            <!-- tomcat7 -->
            <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.2</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>
    
  • jdbc.properties
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm
    jdbc.username=root
    jdbc.password=123456
    
  • 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:/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
    
    
  • web.xml
    <!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>
    
        <!-- 配置加载类路径的配置文件 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
        <!-- 配置解决中文乱码的过滤器 -->
        <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>
    
        <!-- 配置Spring的监听器 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 -->
        <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    
  • 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="pers.ylq">
            <!-- 配置要忽略的注解 -->
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!-- Spring整合MyBatis   -->
        <!-- 读取数据库配置文件 -->
        <context:property-placeholder location="classpath:jdbcConfig.properties"/>
        <!-- 配置C3P0的连接池对象 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
    
        <!-- 配置SqlSession的工厂 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 配置 下划线转驼峰式 -->
            <property name="configuration">
                <bean class="org.apache.ibatis.session.Configuration">
                    <property name="mapUnderscoreToCamelCase" value="true"/>
                </bean>
            </property>
        </bean>
    
        <!-- 配置扫描dao的包 -->
        <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="pers.ylq.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*" propagation="SUPPORTS" read-only="true"/>
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    
        <!-- 配置AOP增强  -->
        <aop:config>
            <aop:advisor advice-ref="txAdvice" pointcut="execution(* pers.ylq.service.impl.*ServiceImpl.*(..))"/>
        </aop:config>
    </beans>
    
  • 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="pers.ylq">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!-- 配置视图解析器 -->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- JSP文件所在的目录 -->
            <property name="prefix" value="/WEB-INF/pages/"/>
            <!-- 文件的后缀名 -->
            <property name="suffix" value=".jsp"/>
        </bean>
    
        <!-- 设置静态资源不过滤 -->
        <mvc:resources location="/css/" mapping="/css/**"/>
        <mvc:resources location="/images/" mapping="/images/**"/>
        <mvc:resources location="/js/" mapping="/js/**"/>
    
    
        <!-- 开启对SpringMVC注解的支持 -->
        <mvc:annotation-driven/>
    
    </beans>
    
  • controller.AccountController
    package pers.ylq.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import pers.ylq.domain.Account;
    import pers.ylq.service.AccountService;
    
    import java.util.List;
    
    @Controller
    @RequestMapping("/account")
    public class AccountController {
        @Autowired
        private AccountService accountService;
    
        @RequestMapping("/saveAccount")
        public String saveAccount(Account account){
            System.out.println("表现层:保存账户...");
            accountService.saveAccount(account);
            return "list";
        }
    
        @RequestMapping("/findAll")
        public String findAll() {
            System.out.println("表现层:查询所有账户...");
            List<Account> list = accountService.findAll();
            for (Account account : list) {
                System.out.println(account);
            }
            return "list";
        }
    }
    
  • dao.AccountDao
    package pers.ylq.dao;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    import org.springframework.stereotype.Repository;
    import pers.ylq.domain.Account;
    
    import java.util.List;
    
    @Repository
    public interface AccountDao {
        @Insert("insert into account(name,money) values(#{name},#{money})")
        public void saveAccount(Account account);
    
        @Select("select * from account")
        public List<Account> findAll();
    }
    
  • domain.Account
    package pers.ylq.domain;
    
    import java.io.Serializable;
    
    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 +
                    '}';
        }
    }
    
  • service.AccountService
    package pers.ylq.service;
    
    import pers.ylq.domain.Account;
    
    import java.util.List;
    
    public interface AccountService {
        void saveAccount(Account account);
    
        List<Account> findAll();
    }
    
  • service.impl.AccountServiceImpl
    package pers.ylq.service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import pers.ylq.dao.AccountDao;
    import pers.ylq.domain.Account;
    import pers.ylq.service.AccountService;
    
    import java.util.List;
    
    @Service("accountService")
    public class AccountServiceImpl implements AccountService {
    
        @Autowired
        private AccountDao accountDao;
    
        @Override
        public void saveAccount(Account account) {
            System.out.println("业务层:保存账号...");
            accountDao.saveAccount(account);
        }
    
        @Override
        public List<Account> findAll() {
            System.out.println("业务层:查询所有账号...");
            return accountDao.findAll();
        }
    }
    
  • index.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <a href="account/findAll">查询所有</a>
    <h3>测试保存账号方法</h3>
    <form action="account/saveAccount" method="post">
        姓名:<input type="text" name="name">
        <br>
        金额:<input type="text" name="money">
        <br>
        <input type="submit" value="提交">
    </form>
    </body>
    </html>
    
  • list.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <h3>跳转成功</h3>
    </body>
    </html>