1. 程式人生 > 實用技巧 >08-SpringMVC之SSM整合案例

08-SpringMVC之SSM整合案例

SSM整合

配置pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    <!--jsp-->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>jstl-api</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
    <dependency>
      <groupId>org.apache.taglibs</groupId>
      <artifactId>taglibs-standard-impl</artifactId>
      <version>1.2.3</version>
    </dependency>

    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.16</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <!--mybatis-spring-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!--c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    <!--spring-mvc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <!--spring-tx-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
    <!--aspectj-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.0</version>
    </dependency>
    <!--spring-test-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
    <!--spring-jdbc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <!--JSON依賴包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.10.3</version>
    </dependency>
    <!--JSON依賴包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.10.3</version>
    </dependency>
    <!--JSON依賴包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.10.3</version>
    </dependency>
</dependencies>

配置spring的配置檔案(此處為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
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--開啟註解掃描,不包含@Controller註解-->
    <context:component-scan base-package="com.whether">
        <!--配置哪些註解不掃描(controller註解不掃描)-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--Spring 整合Mybatis-->
    <!--配置連線池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/softtesting?serverTimezone=Asia/Shanghai"/>
        <property name="user" value="java"/>
        <property name="password" value="whether-1"/>
    </bean>
    <!--開啟自動駝峰命名規則以及JDBC自動生成主鍵-->
    <bean id="settings" class="org.apache.ibatis.session.Configuration">
        <property name="mapUnderscoreToCamelCase" value="true"></property>
        <property name="useGeneratedKeys" value="true"></property>
    </bean>
    <!--配置SqlSessionFactory工廠-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--掃描pojo包,給包下所有pojo物件起別名-->
        <property name="typeAliasesPackage" value="com.whether.pojo"/>
        <property name="configuration" ref="settings"></property>
    </bean>
    <!--配置Dao介面所在的包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.whether.dao"></property>
    </bean>

    <!--配置Spring框架宣告式事務管理-->
    <!--配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT" />
        </tx:attributes>
    </tx:advice>
    <!--配置AOP增強-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.whether.service.impl.*ServiceImpl.*(..))" />
    </aop:config>

</beans>

配置spring-mvc的配置檔案(此處為spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--開啟Controller的註解掃描(spring的配置檔案中未開啟,此處開啟)-->
    <context:component-scan base-package="com.whether">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--檢視解析器,就是解析某個目錄下的某個型別的檔案-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    
    <!--讓SpringMVC不處理靜態資源,下面兩者選其一-->
    <mvc:default-servlet-handler/>
    <!--過濾的靜態資源(不攔截的靜態資源)-->
    <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
    <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>

    <!--開啟Spring MVC框架註解的支援,開啟後將支援一些Spring-MVC的註解,比如@RequestMapping
		同時將自動載入處理器對映器、處理器介面卡-->
    <mvc:annotation-driven></mvc:annotation-driven>

</beans>

配置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>

    <!--設定Spring配置檔案的路徑-->
    <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>
        <!--攔截所有請求,包括"/xxx.jsp"-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--配置Spring監聽器,預設載入WEB-INF目錄下的applicationContext.xml配置檔案,可以管理ServletContext(建立以及銷燬)
        最好使用,每個webapp建立的時候都會建立一個ServletContext物件,ServletContext物件中將會儲存這個webapp的一些資料(類似於全域性變數)
        以鍵值對的形式儲存,可以用來載入Spring的xml檔案,也可以不使用預設的載入的spring配置檔案路徑而使用<context-param>標籤獲得Spring配置檔案路徑。
    -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--前端控制器-->
    <!--Spring MVC 的Servlet,預設載入WEB-INF/[servlet-name]-servlet.xml 的配置檔案,生成檔案中定義的bean。-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 不使用預設載入的xml配置檔案,使用自定義的配置檔案-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!--啟動順序,1:讓這個Servlet隨Servletp容器一起啟動。-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!--會攔截"/xxx"的請求,注意不會攔截"/xxx.html、/xxx.jsp這些帶字尾的請求"-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

也可以這樣(簡便一些),這樣配置需要在applicationContext.xml中引入spring-mvc.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>

    <!--解決中文亂碼的過濾器-->
    <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>
        <!--攔截所有請求,包括"/xxx.jsp"-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--前端控制器-->
    <!--Spring MVC 的Servlet,預設載入WEB-INF/[servlet-name]-servlet.xml 的配置檔案,生成檔案中定義的bean。-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 不使用預設載入的xml配置檔案,使用自定義的配置檔案-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!--啟動順序,1:讓這個Servlet隨Servletp容器一起啟動。-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!--會攔截"/xxx"的請求,注意不會攔截"/xxx.html、/xxx.jsp這些帶字尾的請求"-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

編寫控制器

package com.whether.controller;

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

@Controller
public class HelloController {
    @RequestMapping(path = "/hello")
    public String sayHello(){
        System.out.println("Hello SpringMVC");
        return "success";
    }
}