欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

框架集成——SpringMVC与MyBatis集成(超详细)

程序员文章站 2022-05-26 08:54:03
...

SpringMVC与MyBatis是我们现在最流行的开发框架组合之一,这里我来整理一下框架的集成搭建过程

前言

使用IDE:IntelliJ IDEA
JDK:1.8

打开IDEA,新建maven工程

第一步:打开IDEA,点击Create New Project
框架集成——SpringMVC与MyBatis集成(超详细)
第二步:
选择新建一个Maven项目,然后从Maven项目模板工具包中选择常用的[maven-archetype-webapp]模板

在这个项目里,有WEB-INF目录,并且有web.xml和一个index.jsp ,选中之后,点击next下一步

框架集成——SpringMVC与MyBatis集成(超详细)
第三步:
输入maven的GroupId和ArtifactId,完成之后选择next

GroupID是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构。
ArtifactID是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称。

框架集成——SpringMVC与MyBatis集成(超详细)
第四步:
查看maven相关配置(一般如果没什么问题,可直接跳过,进行下一步)
框架集成——SpringMVC与MyBatis集成(超详细)
第五步:
设置项目的名称和存放目录,输入完成后,点击Finish完成
框架集成——SpringMVC与MyBatis集成(超详细)
第六步:
完成之后,打开项目,初始化结构如图所示,(maven的pom.xml结构改变时,记得点击右下角出现的:Import Changes)
框架集成——SpringMVC与MyBatis集成(超详细)

完善项目目录结构

我们看到,通过maven模板建立的项目结构并不是我们常用的,此时,我们需要进行一些添加
框架集成——SpringMVC与MyBatis集成(超详细)

如果你新建的文件夹(比如java目录),没有被idea识别,你可以手动设置改变文件夹属性,操作如下
框架集成——SpringMVC与MyBatis集成(超详细)

编辑maven的pom.xml文件,设置项目建造和引入相关依赖

我的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>com.sample.ssm</groupId>
    <artifactId>sample-web</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring-version>4.2.3.RELEASE</spring-version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- java日志: slf4j,log4j,logback,common-looging slf4j是规范/接口 使用:slf4j,logback start-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.7</version>
        </dependency>
        <!-- 实现slf4j接口并整合 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.7</version>
        </dependency>
        <!-- java日志: slf4j,log4j,logback,common-looging slf4j是规范/接口 使用:slf4j,logback end-->

        <!--Servlet相关 start-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--Servlet相关 end-->

        <!-- Json 相关 start-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.38</version>
        </dependency>
        <!-- Json 相关 end-->

        <!--Spring相关 start-->
        <!-- Sping核心依赖 start-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <!-- Sping核心依赖 end-->

        <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>
        <!-- Sping Test相关依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <!--Spring相关 end-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency>


        <!-- 数据库相关的依赖 start-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>

        <!-- DAO框架:MyBatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.0.1</version>
        </dependency>
        <!-- Mybatis自身实现的Spring整合依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/cglib/cglib -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.4</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <!-- 数据库相关的依赖 end-->

        <!--mybatis自动化mapper插件tk.mybatis start-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.3.9</version>
        </dependency>
        <!--mybatis自动化mapper插件tk.mybatis end-->

        <!--mybatis.generator start-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!--mybatis.generator end-->


    </dependencies>
    <build>
        <finalName>sample-admin</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>generator*.*</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <!--mybatis自动生成实体代码的插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.3</version>
                <configuration>
                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>


                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.3</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.3.9</version>
                    </dependency>
                </dependencies>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19</version>
                <configuration>
                    <!-- 跳过maven的Test -->
                    <skip>true</skip>
                    <argLine>-Dfile.encoding=UTF-8</argLine>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

配置Spring,并且集成MyBatis

我们需要集成SpringMVC与MyBatis,所以,我们从ORM框架开始集成,最后在组建Spring MVC,一步一步来,不容易出错。Spring相关的文件这里统一放在resources的spring文件夹下。集成MyBatis的文件为spring-dao.xml,其中需要配置文件:mybatis-config.xml和单独提出数据库连接信息存放文件:jdbc.properties(记得修改自己的数据库连接信息)
spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd ">
    <!-- 配置整合Mybatis过程 -->
    <!-- 配置数据库相关参数 properties的属性:${url} -->
    <!--<context:property-placeholder location="classpath:jdbc.properties"/>-->

    <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!-- dataSourse连接池相关属性 -->
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
    <!--2.配置连接池属性 -->
    <!-- 数据源配置, 使用 Druid 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
        <property name="driverClassName" value="${jdbc.driver}"/>

        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${jdbc.pool.init}"/>
        <property name="minIdle" value="${jdbc.pool.minIdle}"/>
        <property name="maxActive" value="${jdbc.pool.maxActive}"/>

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>

        <property name="validationQuery" value="${jdbc.testSql}"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) -->
        <!-- <property name="poolPreparedStatements"
                   value="true"/>
         <property name="maxPoolPreparedStatementPerConnectionSize"
                   value="20"/>-->
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat"/>
    </bean>

    <!--3.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!--配置mybatis全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--扫描entity包,使用别名,多个用;隔开 -->
        <property name="typeAliasesPackage" value="entity"/>
        <!--扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <value>
                            dialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>
    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.sample.ssm.mapper"/>
        <property name="properties">
            <value>
                mappers=tk.mybatis.mapper.common.Mapper
            </value>
        </property>
    </bean>
</beans>

jdbc.properties

#jdbc settings
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1/sample-web?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345

#pool settings
jdbc.pool.init=1
jdbc.pool.minIdle=3
jdbc.pool.maxActive=20

#jdbc.testSql=SELECT 'x'
jdbc.testSql=SELECT 'x' FROM DUAL

mybatis-config.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>
    <!--配置全局属性-->
    <settings>
        <!--使用jdbc的getGeneratekeys获取自增主键值-->
        <setting name="useGeneratedKeys" value="true"/>
        <!--使用列别名替换别名  默认true
        select name as title form table;
        -->
        <setting name="useColumnLabel" value="true"/>

        <!--开启驼峰命名转换-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>

        <!--打印sql日志-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>

构建数据结构

我们需要一个简单的数据进行测试,这里我就建立一张user_info表吧,

/*
Navicat MySQL Data Transfer

Source Server         : 本地
Source Server Version : 50557
Source Host           : 127.0.0.1:3306
Source Database       : sample-web

Target Server Type    : MYSQL
Target Server Version : 50557
File Encoding         : 65001

Date: 2018-08-24 09:31:45
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user_info
-- ----------------------------
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  PRIMARY KEY (`user_id`,`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user_info
-- ----------------------------
INSERT INTO `user_info` VALUES ('1', '用户1');
INSERT INTO `user_info` VALUES ('2', '用户2');

MyBatis集成完成后,进行调试

在框架的集成过程中,我们得一步一步来,保证每一步都不会出错才能顺利得进行下去。现在,我们对user_info这个字段进行操作,主要是:建立实体类UserInfo.java,建立Mapper类,UserInfoMapper.java,建立映射文件UserInfoMapper.xml,具体分别如下:
UserInfo.java

package com.sample.ssm.model;

/**
 * @author yuyufeng
 * @date 2018/8/24.
 */
public class UserInfo {
    private Integer userId;
    private String userName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                '}';
    }
}

UserInfoMapper.java

package com.sample.ssm.mapper;

import com.sample.ssm.model.UserInfo;
import org.apache.ibatis.annotations.Param;

/**
 * @author yuyufeng
 * @date 2018/8/24.
 */
public interface UserInfoMapper {
    /**
     * 根据ID获取单个对象
     * @param userId
     * @return
     */
    UserInfo selectOne(@Param("userId") Integer userId);
}

UserInfoMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sample.ssm.mapper.UserInfoMapper">
    <resultMap id="BaseResultMap" type="com.sample.ssm.model.UserInfo">
        <id column="user_id" jdbcType="INTEGER" property="userId" />
        <result column="user_name" jdbcType="VARCHAR" property="userName" />
    </resultMap>
    <sql id="Base_Column_List">
        <!--
          WARNING - @mbg.generated
        -->
        user_id, user_name
    </sql>
    <select id="selectOne" resultType="com.sample.ssm.model.UserInfo">
        SELECT user_id, user_name FROM user_info WHERE user_id = #{userId,jdbcType=INTEGER}
    </select>
</mapper>

框架集成——SpringMVC与MyBatis集成(超详细)
目前项目的结构如上图所示。
接着,我们需要使用Junit结合Spring进行调试:
在test目录下建立UserInfoMapperTest.java

package com.sample.ssm.mapper;

import com.sample.ssm.model.UserInfo;
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;

/**
 * @author yuyufeng
 * @date 2018/8/24.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class UserInfoMapperTest {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Test
    public void testSelectOne(){
        UserInfo userInfo = userInfoMapper.selectOne(1);
        System.out.println(userInfo);
    }
}

执行调试debug:
框架集成——SpringMVC与MyBatis集成(超详细)
返回结果如下图所示:
框架集成——SpringMVC与MyBatis集成(超详细)
到这里,我们已经成功集成Spring+MyBatis了

集成Spring MVC

首先,我们还是在xml进行一些Spring MVC的基础配置,具体内容写在注释里
spring-web.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.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.sample.ssm.action"></context:component-scan>

    <!--配置springmvc -->
    <!--1:开始SpringMVC注解模式 -->
    <!--简化配置: -->
    <!--1)自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter -->
    <!--2)提供一些列:数据绑定,数字和日期的format @NumberFormat @DataTimeFormart,xml,json 默认读写支持。 -->
    <!-- 类型转化 -->
    <bean id="conversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    </bean>

    <!-- 校验器 -->
    <bean id="validator"
          class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- hibernate校验器 -->
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
        <!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties -->
        <property name="validationMessageSource" ref="messageSource" />
    </bean>

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="useCodeAsDefaultMessage" value="false"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven conversion-service="conversionService"
                           validator="validator">
        <mvc:message-converters register-defaults="true">
            <!-- 将Jackson2HttpMessageConverter的默认格式化输出为true -->
            <!-- 配置Fastjson支持 -->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <!--<value>WriteMapNullValue</value>-->
                        <value>QuoteFieldNames</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <context:component-scan base-package="com.sample.ssm.action"/>

    <!--2.静态资源默认servlet配置 -->
    <!-- 1).加入对静态资源处理:js,gif,png 2).允许使用 "/" 做整体映射 -->
    <mvc:default-servlet-handler/>
    <mvc:resources location="/static/" mapping="/static/**"/>


    <!--3:配置JSP 显示ViewResolver -->
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--拦截器 -->
    <!-- <mvc:interceptors>
         <mvc:interceptor>
             <mvc:mapping path="/**"/>
             <bean class="com.sample.ssm.interceptor.RootInterceptor"></bean>
         </mvc:interceptor>
     </mvc:interceptors>-->


    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->
        <property name="defaultErrorView" value="success"></property>
        <!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->
        <property name="exceptionAttribute" value="message"></property>
    </bean>
</beans>

接着,我们需要在web项目启动的时候去加载这些Spring配置文件,打开web.xml,常用配置如下
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1"
         metadata-complete="false">
  <display-name>sample-web</display-name>

  <!-- post乱码过虑器 start-->
  <filter>
    <filter-name>encodingFilter</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>

  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- post乱码过虑器 end-->

  <!--配置DispatcherServlet -->
  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- 配置SpringMVC 需要配置的文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-*.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <!--默认匹配所有请求 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

建立Controller和jsp

UserController.class

package com.sample.ssm.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author yuyufeng
 * @date 2018/8/24.
 */
@Controller
public class UserController {

    @RequestMapping("/user")
    private String toUser(){
        return "user";
    }
}

WEB-INF/jsp/user.jsp

<%--
  Created by IntelliJ IDEA.
  User: yuyufeng
  Date: 2018/8/24
  Time: 10:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户信息</title>
</head>
<body>
<h1>Hello 你好</h1>
</body>
</html>

配置Tomcat

第一步:选择编辑配置
框架集成——SpringMVC与MyBatis集成(超详细)
第二步:选择使用过Tomcat
框架集成——SpringMVC与MyBatis集成(超详细)
第三步:配置Tomcat信息
框架集成——SpringMVC与MyBatis集成(超详细)
第四步:部署war包到Tomcat下
框架集成——SpringMVC与MyBatis集成(超详细)
选择exploded版本可以在运行过程中进行编译
框架集成——SpringMVC与MyBatis集成(超详细)
设置及时更新class文件,为了调试时编译
框架集成——SpringMVC与MyBatis集成(超详细)
第五步:点击debug启动tomcat
框架集成——SpringMVC与MyBatis集成(超详细)
启动成功后,打开浏览器,输入http://127.0.0.1:8080/user,打开网页,访问到如下图,
框架集成——SpringMVC与MyBatis集成(超详细)
此时此刻,Spring MVC已经部署完毕;

SpringMVC 与 MyBatis的使用

接下来,我们就要在Controller中使用Spring中已经集成的MyBatis了,在此,我们可以构建常用的目录,加入Service层
在service中,我们经常使用Spring集成的事务,此时,我们增加一个Spring配置
spring-service.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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <context:component-scan base-package="com.sample.ssm.service.impl"></context:component-scan>

    <!--配置事务管理器(mybatis采用的是JDBC的事务管理器)-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置基于注解的声明式事务,默认使用注解来管理事务行为-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

此时的目录结构:
框架集成——SpringMVC与MyBatis集成(超详细)
现在,我们建立Service类,IUserService.java,UserServiceImpl.java
IUserService.java

package com.sample.ssm.service;

import com.sample.ssm.model.UserInfo;

/**
 * @author yuyufeng
 * @date 2018/8/24.
 */
public interface IUserService {
    /**
     * 根据userId获取用户
     * @param userId
     * @return
     */
    UserInfo getUserInfoByUserId(Integer userId);
}

UserServiceImpl.java

package com.sample.ssm.service.impl;

import com.sample.ssm.mapper.UserInfoMapper;
import com.sample.ssm.model.UserInfo;
import com.sample.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yuyufeng
 * @date 2018/8/24.
 */
@Service
public class UserServiceImpl implements IUserService{
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo getUserInfoByUserId(Integer userId) {
        return userInfoMapper.selectOne(userId);
    }
}

接着,在Controller中引用,

package com.sample.ssm.action;

import com.sample.ssm.model.UserInfo;
import com.sample.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author yuyufeng
 * @date 2018/8/24.
 */
@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/user")
    private String toUser(Model model,Integer userId){
        UserInfo userInfo = userService.getUserInfoByUserId(userId);
        model.addAttribute("user", userInfo);
        return "user";
    }
}

在jsp中,使用EL表达式接收:

<%--
  Created by IntelliJ IDEA.
  User: yuyufeng
  Date: 2018/8/24
  Time: 10:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户信息</title>
</head>
<body>
<h1>Hello 你好</h1>
<p>用户ID:${user.userId}</p>
<p>用户NAME:${user.userName}</p>
</body>
</html>

编辑完成后,重启Tomcat,打开地址http://127.0.0.1:8080/user?userId=1,效果如下
框架集成——SpringMVC与MyBatis集成(超详细)
到这里,SpringMVC与MyBatis集成基础已经完成,已经可以进行基本的开发了。至于更细的操作,比如使用generator生成Java代码,使用TKMybatis减少MyBatis开发过程中的代码编写,JSP项目的页面便于开发的结构等,都将集成在此项目的版本中,请待今后的文章更新吧。
代码地址:https://github.com/yuyufeng1994/sample-web-ssm/tree/v1