1. 程式人生 > >框架整合——SpringMVC與MyBatis整合(超詳細)

框架整合——SpringMVC與MyBatis整合(超詳細)

SpringMVC與MyBatis是我們現在最流行的開發框架組合之一,這裡我來整理一下框架的整合搭建過程

前言

使用IDE:IntelliJ IDEA
JDK:1.8

開啟IDEA,新建maven工程

第一步:開啟IDEA,點選Create New Project
這裡寫圖片描述
第二步:
選擇新建一個Maven專案,然後從Maven專案模板工具包中選擇常用的[maven-archetype-webapp]模板

在這個專案裡,有WEB-INF目錄,並且有web.xml和一個index.jsp ,選中之後,點選next下一步

這裡寫圖片描述
第三步:
輸入maven的GroupId和ArtifactId,完成之後選擇next

GroupID是專案組織唯一的識別符號,實際對應JAVA的包的結構,是main目錄裡java的目錄結構。
ArtifactID是專案的唯一的識別符號,實際對應專案的名稱,就是專案根目錄的名稱。

這裡寫圖片描述
第四步:
檢視maven相關配置(一般如果沒什麼問題,可直接跳過,進行下一步)
這裡寫圖片描述
第五步:
設定專案的名稱和存放目錄,輸入完成後,點選Finish完成
這裡寫圖片描述
第六步:
完成之後,開啟專案,初始化結構如圖所示,(maven的pom.xml結構改變時,記得點選右下角出現的:Import Changes)
這裡寫圖片描述

完善專案目錄結構

我們看到,通過maven模板建立的專案結構並不是我們常用的,此時,我們需要進行一些新增
這裡寫圖片描述

如果你新建的資料夾(比如java目錄),沒有被idea識別,你可以手動設定改變資料夾屬性,操作如下
這裡寫圖片描述

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

這裡寫圖片描述
目前專案的結構如上圖所示。
接著,我們需要使用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:
這裡寫圖片描述
返回結果如下圖所示:
這裡寫圖片描述
到這裡,我們已經成功整合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

第一步:選擇編輯配置
這裡寫圖片描述
第二步:選擇使用過Tomcat
這裡寫圖片描述
第三步:配置Tomcat資訊
這裡寫圖片描述
第四步:部署war包到Tomcat下
這裡寫圖片描述
選擇exploded版本可以在執行過程中進行編譯
這裡寫圖片描述
設定及時更新class檔案,為了除錯時編譯
這裡寫圖片描述
第五步:點選debug啟動tomcat
這裡寫圖片描述
啟動成功後,開啟瀏覽器,輸入http://127.0.0.1:8080/user,開啟網頁,訪問到如下圖,
這裡寫圖片描述
此時此刻,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>

此時的目錄結構:
這裡寫圖片描述
現在,我們建立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整合基礎已經完成,已經可以進行基本的開發了。至於更細的操作,比如使用generator生成Java程式碼,使用TKMybatis減少MyBatis開發過程中的程式碼編寫,JSP專案的頁面便於開發的結構等,都將整合在此專案的版本中,請待今後的文章更新吧。
程式碼地址:https://github.com/yuyufeng1994/sample-web-ssm/tree/v1