天天看點

springmvc配置的全解析,緻敬即将遠去的mvc

springmvc配置的全解析,緻敬即将遠去的mvc

springmvc最為人稱道的就是過多的xml配置,繁瑣且複雜,本文将按照加載順序逐一介紹配置,附上檔案結構。

springmvc配置的全解析,緻敬即将遠去的mvc

1.加載web.xml

啟動時,第一步加載web.xml,初始化上線文與核心控制器DispatcherServlet 。

<?xml version="1.0" encoding="UTF-8"?>    
<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">    
    <display-name>Archetype Created Web Application</display-name>    
        
    <welcome-file-list>    
        <welcome-file>/index.jsp</welcome-file>    
    </welcome-file-list>    
        
    <!-- 加載applicationContext.xml配置檔案 -->    
    <context-param>    
         <param-name>contextConfigLocation</param-name>    
        <param-value>classpath:applicationContext.xml</param-value>    
    </context-param>    
    
    <!-- 建立WebApplicationContext(上下文) -->
    <listener>    
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
    </listener>    
        
    <!-- 編碼過濾器 -->    
    <filter>    
        <filter-name>encodingFilter</filter-name>    
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    
        <async-supported>true</async-supported>    
        <init-param>    
            <param-name>encoding</param-name>    
            <param-value>UTF-8</param-value>    
        </init-param>    
    </filter>    
    <filter-mapping>    
        <filter-name>encodingFilter</filter-name>    
        <url-pattern>/*</url-pattern>    
    </filter-mapping>    
        
    <!-- 加載DispatcherServlet   -->    
    <servlet>    
        <servlet-name>SpringMVC</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>    
        <async-supported>true</async-supported>    
    </servlet>    
    <servlet-mapping>    
        <servlet-name>SpringMVC</servlet-name>    
        <url-pattern>/</url-pattern>    
    </servlet-mapping>    
        
</web-app>       

2.讀取applicationContext.xml

之後,會讀取 applicationContext.xml,該xml中引用了spring-dao.xml,spring-db.xml,spring-tx.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:websocket="http://www.springframework.org/schema/websocket"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/mvc 
                            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
                            http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd                        
                            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
    <!-- 自動掃描 讀取各個類的spring注解 并注入spring工廠中 使項目支援依賴注入 -->
    <context:component-scan base-package="com" />

    <!-- 導入DAO配置 -->
    <import resource="spring-dao.xml" />

    <!-- 導入資料庫配置 -->
    <import resource="spring-db.xml" />

    <!-- 導入事務配置 -->
    <import resource="spring-tx.xml" />
</beans>      

3.讀取spring-dao.xml

mybatis配置,擷取dao層所在的位置。

<?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:p="http://www.springframework.org/schema/p"
       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-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">


    <!-- DAO接口所在包名,Spring會自動查找其下的類 并且将所有的dao接口封裝成beanDefinitions(spring bean) 裝載進入spring factory -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--basePackage指定要掃描的包,在此包之下的映射器都會被搜尋到。 可指定多個包,包與包之間用逗号或分号分隔-->
        <property name="basePackage" value="com.dao" />
        <!-- spring-db.xml中的 sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

</beans>      

4.讀取 spring-db.xml

這裡是配置資料庫連接配接與mybatis的相關配置。。

<?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:p="http://www.springframework.org/schema/p"
       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-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 引入配置檔案  配置的資料庫資訊-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <!-- 資料庫連接配接池  -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <!-- 初始化連接配接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 連接配接池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 連接配接池最大空閑 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 連接配接池最小空閑 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 擷取連接配接最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射檔案  将mapper.xml解析成SqlSessionFactoryBean并傳回,在查詢時
           可以擷取SqlSessionFactory,并通過代理模調用到-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 引入mysql資料源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml檔案 -->
        <property name="mapperLocations" value="classpath:com/mappers/*.xml"></property>
    </bean>

</beans>      

這裡連接配接資料庫需要知道資料庫的賬号密碼,為了統一管理,将資料庫配置放在jdbc.properties。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql
username=root    
password=root    
initialSize=0    

maxActive=20    
maxIdle=20    
minIdle=1    
maxWait=60000         

5.讀取spring-tx.xml

進行事務配置 通過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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->

    <!-- 如果在同一個service類中定義的兩個方法, 内層REQUIRES_NEW并不會開啟新的事務,save和update中復原都會導緻整個事務的復原 
        如果在不同的service中定義的兩個方法, 内層REQUIRES_NEW會開啟新的事務,并且二者獨立,事務復原互不影響 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
    <!-- Spring程式設計式事務 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="insertInto" propagation="REQUIRED"
                read-only="false" rollback-for="java.lang.Exception" />
        </tx:attributes>
    </tx:advice>

    <!-- 事務處理管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 為spring-db.xml中dataSource資料庫連接配接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>


</beans>      

6.讀取spring-mvc.xml

該配置主要是配置spring mvc核心功能,如aop,注解掃描位置,攔截器等。

<?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc                   
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/task                   
                        http://www.springframework.org/schema/task/spring-task-3.0.xsd
                        http://www.springframework.org/schema/aop                        
                        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!--避免IE執行AJAX時,傳回JSON出現下載下傳檔案 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 添加注解驅動 -->
    <mvc:annotation-driven />
    <!-- 設定使用注解的類所在的包 mvc隻需要掃描controller就可以-->
    <context:component-scan base-package="com.controller" />

    <!-- 完成請求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 -->
            </list>
        </property>
    </bean>
    
    <!-- 定義跳轉的檔案的前字尾 ,視圖模式配置 由于現在基本都是前後端分離 一般沒什麼軟用 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裡的配置我的了解是自動給後面action的方法return的字元串加上字首和字尾,變成一個 可用的url位址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- SpringMVC上傳檔案時,需要配置MultipartResolver處理器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 預設編碼 -->
        <property name="defaultEncoding" value="utf-8" />
        <!-- 檔案大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 記憶體中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>
    
    <!-- aop的配置 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
    <!-- 定時任務配置 -->
    <task:executor id="executor" pool-size="10"
        queue-capacity="128" />
    <task:scheduler id="scheduler" pool-size="10" />
    <task:annotation-driven executor="executor"
        scheduler="scheduler" proxy-target-class="true" />
        
    <!-- 攔截器配置 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--配置攔截器的作用路徑 -->
            <mvc:mapping path="/**" />
            <!--定義在<mvc:interceptor>下面的表示比對指定路徑的請求才進行攔截 com.HandlerInterceptor為攔截器類名 -->
            <bean class="com.HandlerInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

</beans>      

7.攔截器類

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class HandlerInterceptor extends HandlerInterceptorAdapter {

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

        System.out.println("11111111");
    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        System.out.println("222222222");
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("333333333");
        return true;
    }
}      

8.aop切面

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Configuration
public class IntercepterInterface {

    private static final Logger LOG = LoggerFactory.getLogger(IntercepterInterface.class);
    @Pointcut("execution(* com.controller.*.*(..))")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        LOG.info("HTTP METHOD : " + request.getMethod());
        LOG.info("IP : " + request.getRemoteAddr());
        LOG.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        System.out.println("aaa");

    }

    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        System.out.println("bbb");

    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ob = pjp.proceed();
        System.out.println("ccc");
        return ob;
    }
}