spring+springmvc+mybatis(ssm)整合


layout: post
author: zjhChester
header-img: img/post-bg-os-metro.jpg
catalog: true
tags:
- ssm整合


spring+springmvc+mybatis(ssm)整合

1.前期準備

1.構建maven項目,勾選骨架構建,勾選web-app

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-S8LwyYnG-1580546011637)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570857284829.png)]

2.快速構建項目在maven引入的地方加上一組鍵值對:archetypeCatalog internal

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-38vqSxA4-1580546011638)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570857482777.png)]

​ 3.構建pom座標依賴

 <!--spring框架核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!--spring web核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!--spring mvc 核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version> 
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
 <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

2.spring spring-mvc mybatis 配置文件構建

2.1.項目結構

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-2blFghhO-1580546011640)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570858617777.png)]

2.2.spring

1.名稱空間:

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

2.註解掃描:

需要注意的是咱們整合三大框架,如果需要用spring的註解開發,咱們應該規避mvc框架中的Controller註解,所以咱們在xml配置文件中應該加入對應的不掃描的配置,如下

applicationContext.xml

 <!--開啓註解掃描-->
        <context:component-scan base-package="cn.tfs">
            <!--不掃描的包-->
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
        </context:component-scan>

2.3.spring-mvc

1.註解掃描:

與上面一樣springmvc需要掃描的註解只包括@Controller的註解,所以我們在掃描中添加過濾器

spring-mvc.xml

<!--掃描註解-->
    <context:component-scan base-package="cn.tfs">
        <!--配置spring-mvc需要掃描的註解-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

2.視圖解析器:

<!--jsp視圖解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <property name="order" value="0" />
    </bean>

3.註解支持:

因爲有時候我們需要用@Response註解去給請求返回字符串內容,那麼有可能會遇到中文的問題,所以這裏我們在開啓註解支持的時候加入對應的編碼轉化的bean

 <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!--配置@Response註解編碼問題-->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=utf-8"></property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

4.靜態資源訪問映射:

<mvc:default-servlet-handler/>
    <!--把符合/js/**匹配規則的請求,映射到目錄/WEB-INF/js/下-->
    <mvc:resources mapping="/js/**" location="WEB-INF/js/"/>
    <mvc:resources mapping="/img/**" location="WEB-INF/img/"/>
    <mvc:resources mapping="/css/**" location="WEB-INF/css/"/>

5.web.xml配置:

web-app的名稱空間

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

注意:如果有報紅,咱們就把過濾器丟在控制器前面

另外我們還需要解決前端傳輸過來的數據中文亂碼的問題---->過濾器

<!--過濾器-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <!--字符編碼過濾器   解決中文亂碼的問題-->
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

以及web.xml的前端控制器

 <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--讀取配置文件讀取-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:spring-mvc.xml</param-value>
    </init-param>
    <!--在服務器開啓的時候裝載-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

2.4.mybatis

使用了properties導入參數的方法,使代碼可讀性更高

db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaee?serverTimezone=GMT&useSSL=false&allowPublicKeyRetrieval=true
username=root
password=123

mybatisConfig.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>
    <!-- 1、mybatis使用properties來引入外部properties配置文件的內容
    resource 引入類路徑下資源
    url 引入網絡路徑或磁盤路徑下資源 -->
    <properties resource="db.properties"></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置數據庫連接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="DaoMapper.xml"></mapper>
        <!--掃描包的形式裝配mapper-->
        <!--<package name="cn.tfs.yunge.dao"></package>-->
    </mappers>
</configuration>

3.整合

3.1.確保每個框架都可以獨立正常運行

(寫測試程序!!!)

3.2.整合spring,springmvc

1.首先確保sping的配置文件applicationContext.xml裏面的掃描包確實是排除了@Controller的

2.確保spring-mvc的配置文件spring-mvc.xml裏面的掃描包確實是只包含@Controller的

3.(重要)在web項目中,我們如果發起請求,那麼肯定web.xml只會解析到spring-mvc.xml的配置文件

<!--讀取配置文件讀取-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:spring-mvc.xml</param-value>
    </init-param>

那麼就解析不到spring的配置文件,所以service也不會被注入到IoC容器中,所以我們需要在web.xml配置一個spring的監聽器,在服務器開啓的時候就把spring的配置文件applicationContext.xml給加載了:

  <!--spring監聽器   默認加載WEB-INF/下的applicationContext.xml文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--設置配置文件路徑-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
  </context-param>

4.實現:

UserServiceImpl.java

@Service("userService")
public class UserServiceImpl implements UserService{
     public List<User> findUser(User user) {
        System.out.println("Service findUser 執行...");
        return  dao.findUser(user);

    }
}

HelloController.java

 @Controller
public class HelloController {
    @Autowired
    private UserService userService;

    @RequestMapping("/1")
    public String index(){
        User user = new User();
        userService.findUser(user);
        return "index";
    }
}

測試結果

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-2LQEAZTz-1580546011641)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570863946084.png)]

3.3.整合spring mybatis

1.在業務層調用dao的原理也是一樣的,唯一不同的是這裏我們使用的是代理Dao,他是個接口,所以我們要想辦法把代理下實現類也給裝配到IoC容器中

話不多說咱們看spring的配置文件applicationContext.xml

<!--整合mybatis-->
    <!--配置連接池-->
    <!--引入db.properties數據庫配置信息-->
    <context:property-placeholder location="classpath*:db.properties"></context:property-placeholder>
    <bean id="pooledDataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
        <property name="driver" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!--自動提交事務-->
        <property name="defaultAutoCommit" value="true"></property>
    </bean>
    <!--配置SQLSessionFactory工廠-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--將上面的連接池注入到該工廠-->
        <property name="dataSource" ref="pooledDataSource"></property>
        <!--掃描mapper所在的包-->
        <property name="mapperLocations">
            <list>
                <value>classpath*:cn/tfs/yunge/dao/*.xml</value>
            </list>
        </property>
    </bean>
    <!--配置Dao接口的所在包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.tfs.yunge.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
    </bean>

編寫了上述連接池等信息之後 咱們的mybatis全局配置文件就可以刪除了,之前導入在mybatisConfig.xml文件的db.properties文件以spring-context的方式引入applicationContext.xml

<context:property-placeholder location="classpath*:db.properties"></context:property-placeholder>

2.上述連接池和配置SQLSessionFactory工廠需要引入兩個之前spring-mvc沒有用到過的座標依賴(jar包)

2.1.連接池:事務包tx和jdbc

<!--事務管理核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
 	    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

2.2.配置SQLSessionFactory工廠和配置Mapper的所在包:org.mybatis的包org.apache.ibatis.datasource.pooled.PooledDataSource mybatis的連接池包

 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

3.UserServiceImpl.java

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private Dao dao;
    @Override
    public List<User> findUser(User user) {
        System.out.println("Service findUser 執行...");
        return dao.findUser(user);
    }
    @Override
    public int insertUser(User user) {
        System.out.println("Service insertUser 執行...");
        return dao.insertUser(user);
    }

HelloController.java

@Controller
public class HelloController {
    @Autowired
    private UserService userService;

    @RequestMapping("/1")
    public String findUser(Model model){
        User user = new User();
        user.setUsername("zjh");
        model.addAttribute("result", userService.findUser(user));
        return "index";
    }
    @RequestMapping("/2")
    public String insertUser(Model model){
        User user = new User();
        user.setUsername("zjh");
        user.setPassword("123");
        model.addAttribute("result",userService.insertUser(user));
        return "index";
    }
}

測試:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-G2Ybm11X-1580546011642)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570873585507.png)]

Δ踩坑:

1.pom.xml座標:

spring-tx spring-jdbc事務管理導入,mybatis-spring包的導入

2.db.properties的鍵最好加個jdbc.xxx

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/javaee?serverTimezone=GMT&useSSL=false&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123

3.最坑的問題就是java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransaction.getTimeout()Ljava/lang/Integer;異常

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-bgaxcVg0-1580546011642)(/mdImg/spring+springmvc+mybatis%EF%BC%88ssm%EF%BC%89%E6%95%B4%E5%90%88.assets/1570873725282.png)]

原因是適配版本問題,這個問題搞了我一個半小小時。。。手動沮喪

4.最後一個就是需要加入pom.xml的靜態資源

<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>

不然會找不到*mapper.xml或者.properties ,這個是解決nested exception is org.apache.ibatis.binding.BindingExceptio這個異常的加粗樣式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章