1. 程式人生 > >深入理解Spring MVC 思想

深入理解Spring MVC 思想

目錄 

一、前言 二、spring mvc 核心類與介面 三、spring mvc 核心流程圖

四、spring mvc DispatcherServlet說明

五、spring mvc 父子上下文的說明

六、springMVC-mvc.xml 配置檔案片段講解  七、spring mvc 如何訪問到靜態的檔案,如jpg,js,css

八、spring mvc 請求如何對映到具體的Action中的方法

九、 spring mvc 中的攔截器: 十、 spring mvc 如何使用攔截器

十一、 spring mvc 如何實現全域性的異常處理

十二、 spring mvc 如何把全域性異常記錄到日誌中

十三、 如何給spring3 MVC中的Action做JUnit單元測試

十四、 spring mvc 轉發與重定向 (帶引數重定向)

十五、 spring mvc 處理ajax請求

十六、 spring mvc 關於寫幾個配置檔案的說明 

十七、 spring mvc 如何取得Spring管理的bean

十八、 spring mvc 多檢視控制器

十九、 <mvc:annotation-driven /> 到底做了什麼工作  二十、 本文中springMVC.xml配置檔案是核心,這裡給一個下載地址

一、前言:

為開發團隊選擇一款優秀的MVC框架是件難事兒,在眾多可行的方案中決擇需要很高的經驗和水平。你的一個決定會影響團隊未來的幾年。要考慮方面太多:

1、簡單易用,以提高開發效率。使小部分的精力在框架上,大部分的精力放在業務上。

2、效能優秀,這是一個最能吸引眼球的話題。

3、儘量使用大眾的框架(避免使用小眾的、私有的框架),新招聘來的開發人員有一些這方面技術積累,減低人員流動再適應的影響。

如果你還在為這件事件發愁,本文最適合你了。選擇Spring MVC吧。

Spring MVC是當前最優秀的MVC框架,自從Spring 2.5版本釋出後,由於支援註解配置,易用性有了大幅度的提高。Spring 3.0更加完善,實現了對Struts 2的超越。現在越來越多的開發團隊選擇了Spring MVC。

Struts2也是非常優秀的MVC構架,優點非常多比如良好的結構,攔截器的思想,豐富的功能。但這裡想說的是缺點,Struts2由於採用了值棧、OGNL表示式、struts2標籤庫等,會導致應用的效能下降,應避免使用這些功能。而Struts2的多層攔截器、多例項action效能都很好。可以參考我寫的一篇關於Spring MVC與Struts2與Servlet比較的文章

《Struts2、SpringMVC、Servlet(Jsp)效能對比 測試》

Spring3 MVC的優點:

1、Spring3 MVC使用簡單,學習成本低。學習難度小於Struts2,Struts2用不上的多餘功能太多。呵呵,當然這不是決定因素。

2、Spring3 MVC很容易就可以寫出效能優秀的程式,Struts2要處處小心才可以寫出效能優秀的程式(指MVC部分)

3、Spring3 MVC的靈活是你無法想像的,Spring框架的擴充套件性有口皆碑,Spring3 MVC當然也不會落後,不會因使用了MVC框架而感到有任何的限制。

Struts2的眾多優點:

1、老牌的知名框架,從Struts1起積累了大量使用者群體。技術文件豐富。

2、其它方面略...   (呵呵,是不是不公平?)

二、核心類與介面:

先來了解一下,幾個重要的介面與類。現在不知道他們是幹什麼的沒關係,先混個臉熟,為以後認識他們打個基礎。

DispatcherServlet   -- 前置控制器

HandlerMapping介面 -- 處理請求的對映

HandlerMapping介面的實現類:

SimpleUrlHandlerMapping  通過配置檔案,把一個URL對映到Controller

DefaultAnnotationHandlerMapping  通過註解,把一個URL對映到Controller類上

HandlerAdapter介面 -- 處理請求的對映

AnnotationMethodHandlerAdapter類,通過註解,把一個URL對映到Controller類的方法上

Controller介面 -- 控制器

由於我們使用了@Controller註解,添加了@Controller註解註解的類就可以擔任控制器(Action)的職責,

所以我們並沒有用到這個介面。

HandlerInterceptor 介面--攔截器

無圖,我們自己實現這個介面,來完成攔截的器的工作。

ViewResolver介面的實現類

UrlBasedViewResolver類 通過配置檔案,把一個檢視名交給到一個View來處理

InternalResourceViewResolver類,比上面的類,加入了JSTL的支援

View介面

JstlView類

LocalResolver介面

HandlerExceptionResolver介面 --異常處理

SimpleMappingExceptionResolver實現類

ModelAndView類

無圖。

三、核心流程圖

本圖是我個人畫的,有不嚴謹的地方,大家對付看吧。總比沒的看強。

四、DispatcherServlet說明

使用Spring MVC,配置DispatcherServlet是第一步。

DispatcherServlet是一個Servlet,所以可以配置多個DispatcherServlet。

DispatcherServlet是前置控制器,配置在web.xml檔案中的。攔截匹配的請求,Servlet攔截匹配規則要自已定義,把攔截下來的請求,依據某某規則分發到目標Controller(我們寫的Action)來處理。

“某某規則”:是根據你使用了哪個HandlerMapping介面的實現類的不同而不同。

先來看第一個例子:

Xml程式碼 複製程式碼 收藏程式碼

  1. <web-app>  
  2.     <servlet>  
  3.         <servlet-name>example</servlet-name>  
  4.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  5.         <load-on-startup>1</load-on-startup>  
  6.     </servlet>  
  7.     <servlet-mapping>  
  8.         <servlet-name>example</servlet-name>  
  9.         <url-pattern>*.form</url-pattern>  
  10.     </servlet-mapping>  
  11. </web-app>  
  1. <web-app>  
  2.     <servlet>  
  3.         <servlet-name>example</servlet-name>  
  4.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  5.         <load-on-startup>1</load-on-startup>  
  6.     </servlet>  
  7.     <servlet-mapping>  
  8.         <servlet-name>example</servlet-name>  
  9.         <url-pattern>*.form</url-pattern>  
  10.     </servlet-mapping>  
  11. </web-app>  

 <load-on-startup>1</load-on-startup>是啟動順序,讓這個Servlet隨Servletp容器一起啟動。

 <url-pattern>*.form</url-pattern> 會攔截*.form結尾的請求。

 <servlet-name>example</servlet-name>這個Servlet的名字是example,可以有多個DispatcherServlet,是通過名字來區分的。每一個DispatcherServlet有自己的WebApplicationContext上下文物件。同時儲存的ServletContext中和Request物件中,關於key,以後說明。

在DispatcherServlet的初始化過程中,框架會在web應用的 WEB-INF資料夾下尋找名為[servlet-name]-servlet.xml 的配置檔案,生成檔案中定義的bean。

第二個例子:

Xml程式碼 複製程式碼 收藏程式碼

  1. <servlet>  
  2.     <servlet-name>springMVC</servlet-name>  
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  4.     <init-param>  
  5.         <param-name>contextConfigLocation</param-name>  
  6.         <param-value>classpath*:/springMVC.xml</param-value>  
  7.     </init-param>  
  8.     <load-on-startup>1</load-on-startup>  
  9. </servlet>  
  10. <servlet-mapping>  
  11.     <servlet-name>springMVC</servlet-name>  
  12.     <url-pattern>/</url-pattern>  
  13. </servlet-mapping>  
  1. <servlet>  
  2.     <servlet-name>springMVC</servlet-name>  
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  4.     <init-param>  
  5.         <param-name>contextConfigLocation</param-name>  
  6.         <param-value>classpath*:/springMVC.xml</param-value>  
  7.     </init-param>  
  8.     <load-on-startup>1</load-on-startup>  
  9. </servlet>  
  10. <servlet-mapping>  
  11.     <servlet-name>springMVC</servlet-name>  
  12.     <url-pattern>/</url-pattern>  
  13. </servlet-mapping>  

指明瞭配置檔案的檔名,不使用預設配置檔名,而使用springMVC.xml配置檔案。

其中<param-value>**.xml</param-value> 這裡可以使用多種寫法 1、不寫,使用預設值:/WEB-INF/<servlet-name>-servlet.xml 2、<param-value>/WEB-INF/classes/springMVC.xml</param-value> 3、<param-value>classpath*:springMVC-mvc.xml</param-value> 4、多個值用逗號分隔

Servlet攔截匹配規則可以自已定義,攔截哪種URL合適?  當對映為@RequestMapping("/user/add")時,為例:

1、攔截*.do、*.htm, 例如:/user/add.do

這是最傳統的方式,最簡單也最實用。不會導致靜態檔案(jpg,js,css)被攔截。

2、攔截/,例如:/user/add

可以實現現在很流行的REST風格。很多網際網路型別的應用很喜歡這種風格的URL。

弊端:會導致靜態檔案(jpg,js,css)被攔截後不能正常顯示。想實現REST風格,事情就是麻煩一些。後面有解決辦法還算簡單。

3、攔截/*,這是一個錯誤的方式,請求可以走到Action中,但轉到jsp時再次被攔截,不能訪問到jsp。

五、父子上下文(WebApplicationContext)

如果你使用了listener監聽器來載入配置,一般在Struts+Spring+Hibernate的專案中都是使用listener監聽器的。如下

Java程式碼 複製程式碼 收藏程式碼

  1. <listener>    
  2.   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
  3. </listener>   
  1. <listener>   
  2.   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  3. </listener>   

Spring會建立一個WebApplicationContext上下文,稱為父上下文(父容器) ,儲存在 ServletContext中,key是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的值。

可以使用Spring提供的工具類取出上下文物件:WebApplicationContextUtils.getWebApplicationContext(ServletContext);

DispatcherServlet是一個Servlet,可以同時配置多個,每個 DispatcherServlet有一個自己的上下文物件(WebApplicationContext),稱為子上下文(子容器),子上下文可以訪問父上下文中的內容,但父上下文不能訪問子上下文中的內容。 它也儲存在 ServletContext中,key是"org.springframework.web.servlet.FrameworkServlet.CONTEXT"+Servlet名稱。當一個Request物件產生時,會把這個子上下文物件(WebApplicationContext)儲存在Request物件中,key是DispatcherServlet.class.getName() + ".CONTEXT"。

可以使用工具類取出上下文物件:RequestContextUtils.getWebApplicationContext(request);

說明 :Spring 並沒有限制我們,必須使用父子上下文。我們可以自己決定如何使用。

方案一,傳統型:

父上下文容器中儲存資料來源、服務層、DAO層、事務的Bean。

子上下文容器中儲存Mvc相關的Action的Bean.

事務控制在服務層。

由於父上下文容器不能訪問子上下文容器中內容,事務的Bean在父上下文容器中,無法訪問子上下文容器中內容,就無法對子上下文容器中Action進行AOP(事務)。

當然,做為“傳統型”方案,也沒有必要這要做。

方案二,激進型:

Java世界的“面向介面程式設計”的思想是正確的,但在增刪改查為主業務的系統裡,Dao層介面,Dao層實現類,Service層介面,Service層實現類,Action父類,Action。再加上眾多的O(vo\po\bo)和jsp頁面。寫一個小功能 7、8個類就寫出來了。 開發者說我就是想接點私活兒,和PHP,ASP搶搶飯碗,但我又是Java程式設計師。最好的結果是大專案能做好,小專案能做快。所以“激進型”方案就出現了-----沒有介面、沒有Service層、還可以沒有眾多的O(vo\po\bo)。那沒有Service層事務控制在哪一層?只好上升的Action層。

本文不想說這是不是正確的思想,我想說的是Spring不會限制你這樣做。

由於有了父子上下文,你將無法實現這一目標。解決方案是只使用子上下文容器,不要父上下文容器 。所以資料來源、服務層、DAO層、事務的Bean、Action的Bean都放在子上下文容器中。就可以實現了,事務(註解事務)就正常工作了。這樣才夠激進。

總結:不使用listener監聽器來載入spring的配置檔案,只使用DispatcherServlet來載入spring的配置,不要父子上下文,只使用一個DispatcherServlet,事情就簡單了,什麼麻煩事兒也沒有了。

Java--大專案能做好--按傳統方式做,規規矩矩的做,好擴充套件,好維護。

Java--小專案能做快--按激進方式做,一週時間就可以出一個版本,先上線接受市場(使用者)的反饋,再改進,再反饋,時間就是生命(成本)。

六、springMVC-mvc.xml 配置檔案片段講解 (未使用預設配置檔名)

Xml程式碼 複製程式碼 收藏程式碼

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:context="http://www.springframework.org/schema/context"     
  7.     xmlns:mvc="http://www.springframework.org/schema/mvc"     
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  9.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  10.     http://www.springframework.org/schema/tx    
  11.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
  12.     http://www.springframework.org/schema/context   
  13.     http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  14.     http://www.springframework.org/schema/mvc   
  15.     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  16.     <!-- 自動掃描的包名 -->  
  17.     <context:component-scan base-package="com.app,com.core,JUnit4" ></context:component-scan>  
  18.     <!-- 預設的註解對映的支援 -->  
  19.     <mvc:annotation-driven />  
  20.     <!-- 檢視解釋類 -->  
  21.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  22.         <property name="prefix" value="/WEB-INF/jsp/"/>  
  23.         <property name="suffix" value=".jsp"/><!--可為空,方便實現自已的依據副檔名來選擇檢視解釋類的邏輯  -->  
  24.         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  
  25.     </bean>  
  26.     <!-- 攔截器 -->  
  27.     <mvc:interceptors>  
  28.         <bean class="com.core.mvc.MyInteceptor" />  
  29.     </mvc:interceptors>        
  30.     <!-- 對靜態資原始檔的訪問  方案一 (二選一) -->  
  31.     <mvc:default-servlet-handler/>  
  32.     <!-- 對靜態資原始檔的訪問  方案二 (二選一)-->  
  33.     <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>  
  34.     <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>  
  35.     <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>  
  36. </beans>   
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:context="http://www.springframework.org/schema/context"    
  7.     xmlns:mvc="http://www.springframework.org/schema/mvc"    
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  9.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.     http://www.springframework.org/schema/tx   
  11.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  12.     http://www.springframework.org/schema/context  
  13.     http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  14.     http://www.springframework.org/schema/mvc  
  15.     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  16.     <!-- 自動掃描的包名 -->  
  17.     <context:component-scan base-package="com.app,com.core,JUnit4" ></context:component-scan>  
  18.     <!-- 預設的註解對映的支援 -->  
  19.     <mvc:annotation-driven />  
  20.     <!-- 檢視解釋類 -->  
  21.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  22.         <property name="prefix" value="/WEB-INF/jsp/"/>  
  23.         <property name="suffix" value=".jsp"/><!--可為空,方便實現自已的依據副檔名來選擇檢視解釋類的邏輯  -->  
  24.         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  
  25.     </bean>  
  26.     <!-- 攔截器 -->  
  27.     <mvc:interceptors>  
  28.         <bean class="com.core.mvc.MyInteceptor" />  
  29.     </mvc:interceptors>       
  30.     <!-- 對靜態資原始檔的訪問  方案一 (二選一) -->  
  31.     <mvc:default-servlet-handler/>  
  32.     <!-- 對靜態資原始檔的訪問  方案二 (二選一)-->  
  33.     <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>  
  34.     <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>  
  35.     <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>  
  36. </beans>   

<context:component-scan/> 掃描指定的包中的類上的註解,常用的註解有:

@Controller 宣告Action元件 @Service    宣告Service元件    @Service("myMovieLister")  @Repository 宣告Dao元件 @Component   泛指元件, 當不好歸類時.  @RequestMapping("/menu")  請求對映 @Resource  用於注入,( j2ee提供的 ) 預設按名稱裝配,@Resource(name="beanName")  @Autowired 用於注入,(srping提供的) 預設按型別裝配  @Transactional( rollbackFor={Exception.class}) 事務管理 @ResponseBody @Scope("prototype")   設定bean的作用域

<mvc:annotation-driven /> 是一種簡寫形式,完全可以手動配置替代這種簡寫形式,簡寫形式可以讓初學都快速應用預設配置方案。<mvc:annotation-driven /> 會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,是spring MVC為@Controllers分發請求所必須的。 並提供了:資料繫結支援,@NumberFormatannotation支援,@DateTimeFormat支援,@Valid支援,讀寫XML的支援(JAXB),讀寫JSON的支援(Jackson)。 後面,我們處理響應ajax請求時,就使用到了對json的支援。 後面,對action寫JUnit單元測試時,要從spring IOC容器中取DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,來完成測試,取的時候要知道是<mvc:annotation-driven />這一句註冊的這兩個bean。

如何替換 <mvc:annotation-driven />?他到底做了什麼工作,請看,最後面的 十九節 <mvc:annotation-driven /> 到底做了什麼工作。

<mvc:interceptors/> 是一種簡寫形式。通過看前面的大圖,知道,我們可以配置多個HandlerMapping。<mvc:interceptors/>會為每一個HandlerMapping,注入一個攔截器。其實我們也可以手動配置為每個HandlerMapping注入一個攔截器。

<mvc:default-servlet-handler/> 使用預設的Servlet來響應靜態檔案。

<mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/> 匹配URL  /images/**  的URL被當做靜態資源,由Spring讀出到記憶體中再響應http。

 七、如何訪問到靜態的檔案,如jpg,js,css?

如何你的DispatcherServlet攔截"*.do"這樣的有後綴的URL,就不存在訪問不到靜態資源的問題。 如果你的DispatcherServlet攔截"/",為了實現REST風格,攔截了所有的請求,那麼同時對*.js,*.jpg等靜態檔案的訪問也就被攔截了。 我們要解決這個問題。

目的:可以正常訪問靜態檔案,不可以找不到靜態檔案報404。

  方案一:啟用Tomcat的defaultServlet來處理靜態檔案

Xml程式碼 複製程式碼 收藏程式碼

  1. <servlet-mapping>    
  2.     <servlet-name>default</servlet-name>  
  3.     <url-pattern>*.jpg</url-pattern>      
  4. </servlet-mapping>     
  5. <servlet-mapping>        
  6.     <servlet-name>default</servlet-name>     
  7.     <url-pattern>*.js</url-pattern>     
  8. </servlet-mapping>     
  9. <servlet-mapping>         
  10.     <servlet-name>default</servlet-name>        
  11.     <url-pattern>*.css</url-pattern>       
  12. </servlet-mapping>     
  13. 要配置多個,每種檔案配置一個   
  1. <servlet-mapping>   
  2.     <servlet-name>default</servlet-name>  
  3.     <url-pattern>*.jpg</url-pattern>     
  4. </servlet-mapping>    
  5. <servlet-mapping>       
  6.     <servlet-name>default</servlet-name>    
  7.     <url-pattern>*.js</url-pattern>    
  8. </servlet-mapping>    
  9. <servlet-mapping>        
  10.     <servlet-name>default</servlet-name>       
  11.     <url-pattern>*.css</url-pattern>      
  12. </servlet-mapping>    
  13. 要配置多個,每種檔案配置一個   

要寫在DispatcherServlet的前面, 讓 defaultServlet先攔截請求,這樣請求就不會進入Spring了,我想效能是最好的吧。

Tomcat, Jetty, JBoss, and GlassFish 自帶的預設Servlet的名字 -- "default" Google App Engine 自帶的 預設Servlet的名字 -- "_ah_default" Resin 自帶的 預設Servlet的名字 -- "resin-file" WebLogic 自帶的 預設Servlet的名字  -- "FileServlet" WebSphere  自帶的 預設Servlet的名字 -- "SimpleFileServlet" 

方案二: 在spring3.0.4以後版本提供了mvc:resources ,  使用方法:

Xml程式碼 複製程式碼 收藏程式碼

  1. <!-- 對靜態資原始檔的訪問 -->     
  2. <mvc:resources mapping="/images/**" location="/images/" />  
  1. <!-- 對靜態資原始檔的訪問 -->    
  2. <mvc:resources mapping="/images/**" location="/images/" />  

   /images/**對映到ResourceHttpRequestHandler進行處理,location指定靜態資源的位置.可以是web application根目錄下、jar包裡面,這樣可以把靜態資源壓縮到jar包中。cache-period 可以使得靜態資源進行web cache    如果出現下面的錯誤,可能是沒有配置<mvc:annotation-driven />的原因。  報錯WARNING: No mapping found for HTTP request with URI [/mvc/user/findUser/lisi/770] in DispatcherServlet with name 'springMVC'

使用<mvc:resources/>元素,把mapping的URI註冊到SimpleUrlHandlerMapping的urlMap中, key為mapping的URI pattern值,而value為ResourceHttpRequestHandler, 這樣就巧妙的把對靜態資源的訪問由HandlerMapping轉到ResourceHttpRequestHandler處理並返回,所以就支援classpath目錄,jar包內靜態資源的訪問. 另外需要注意的一點是,不要對SimpleUrlHandlerMapping設定defaultHandler.因為對static uri的defaultHandler就是ResourceHttpRequestHandler, 否則無法處理static resources request.

方案三 ,使用<mvc:default-servlet-handler/>

Xml程式碼 複製程式碼 收藏程式碼

  1. <mvc:default-servlet-handler/>  
  1. <mvc:default-servlet-handler/>  

會把"/**" url,註冊到SimpleUrlHandlerMapping的urlMap中,把對靜態資源的訪問由HandlerMapping轉到org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler處理並返回. DefaultServletHttpRequestHandler使用就是各個Servlet容器自己的預設Servlet.

補充說明:多個HandlerMapping的執行順序問題:

DefaultAnnotationHandlerMapping的order屬性值是:0 <mvc:resources/ >自動註冊的 SimpleUrlHandlerMapping的order屬性值是: 2147483646

<mvc:default-servlet-handler/>自動註冊 的SimpleUrlHandlerMapping 的order屬性值是: 2147483647

spring會先執行order值比較小的。當訪問一個a.jpg圖片檔案時,先通過 DefaultAnnotationHandlerMapping 來找處理器,一定是找不到的,因為我們沒有叫a.jpg的Action。然後再按order值升序找,由於最後一個 SimpleUrlHandlerMapping 是匹配 "/**"的,所以一定會匹配上,就可以響應圖片。

訪問一個圖片,還要走層層匹配。不知效能如何?

最後再說明一下,方案二、方案三 在訪問靜態資源時,如果有匹配的(近似)總攔截器,就會走攔截器。如果你在攔截中實現許可權檢查,要注意過濾這些對靜態檔案的請求。

如何你的DispatcherServlet攔截 *.do這樣的URL字尾,就不存上述問題了。還是有後綴方便。

八、請求如何對映到具體的Action中的方法? 方案一:基於xml配置對映,可以利用SimpleUrlHandlerMapping、BeanNameUrlHandlerMapping進行Url對映和攔截請求。 配置方法略。   方案二:基於註解對映,可以使用DefaultAnnotationHandlerMapping。

Xml程式碼 複製程式碼 收藏程式碼

  1. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">  </bean>   
  1. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">  </bean>   

但前面我們配置了<mvc:annotation-driven />,他會自動註冊這個bean,就不須要我們顯示的註冊這個bean了。  

如何替換 <mvc:annotation-driven />?他到底做了什麼工作,請看,最後面的 十九節 <mvc:annotation-driven /> 到底做了什麼工作。

  以上都可以注入interceptors,實現許可權控制等前置工作。 我們使用第2種,基於註解來使用spring MVC

 並在action類上使用: @Controller @RequestMapping("/user")

轉載請註明出處:原文地址:http://elf8848.iteye.com/blog/875830     九、Spring中的攔截器: Spring為我們提供了: org.springframework.web.servlet.HandlerInterceptor介面,

org.springframework.web.servlet.handler.HandlerInterceptorAdapter介面卡, 實現這個介面或繼承此類,可以非常方便的實現自己的攔截器。   有以下三個方法:   Action之前執行:  public boolean preHandle(HttpServletRequest request,    HttpServletResponse response, Object handler);   生成檢視之前執行  public void postHandle(HttpServletRequest request,    HttpServletResponse response, Object handler,    ModelAndView modelAndView);   最後執行,可用於釋放資源  public void afterCompletion(HttpServletRequest request,    HttpServletResponse response, Object handler, Exception ex)     分別實現預處理、後處理(呼叫了Service並返回ModelAndView,但未進行頁面渲染)、返回處理(已經渲染了頁面)  在preHandle中,可以進行編碼、安全控制等處理;  在postHandle中,有機會修改ModelAndView;  在afterCompletion中,可以根據ex是否為null判斷是否發生了異常,進行日誌記錄。  引數中的Object handler是下一個攔截器。 轉載請註明出處:原文地址:http://elf8848.iteye.com/blog/875830

十、如何使用攔截器? 自定義一個攔截器,要實現HandlerInterceptor介面:

Java程式碼 複製程式碼 收藏程式碼

  1. public class MyInteceptor implements HandlerInterceptor {      
  2.     略。。。   
  3. }    
  1. public class MyInteceptor implements HandlerInterceptor {     
  2.     略。。。  
  3. }    

Spring MVC並沒有總的攔截器,不能對所有的請求進行前後攔截。 Spring MVC的攔截器,是屬於HandlerMapping級別的,可以有多個HandlerMapping ,每個HandlerMapping可以有自己的攔截器。 當一個請求按Order值從小到大,順序執行HandlerMapping介面的實現類時,哪一個先有返回,那就可以結束了,後面的HandlerMapping就不走了,本道工序就完成了。就轉到下一道工序了。 攔截器會在什麼時候執行呢? 一個請求交給一個HandlerMapping時,這個HandlerMapping先找有沒有處理器來處理這個請求,如何找到了,就執行攔截器,執行完攔截後,交給目標處理器。 如果沒有找到處理器,那麼這個攔截器就不會被執行。

在spring MVC的配置檔案中配置有三種方法:

方案一,(近似)總攔截器,攔截所有url

Java程式碼 複製程式碼 收藏程式碼

  1.    <mvc:interceptors>   
  2.     <bean class="com.app.mvc.MyInteceptor" />   
  3. </mvc:interceptors>  
  1.    <mvc:interceptors>  
  2.     <bean class="com.app.mvc.MyInteceptor" />  
  3. </mvc:interceptors>  

為什麼叫“近似”,前面說了,Spring沒有總的攔截器。

<mvc:interceptors/>會為每一個HandlerMapping,注入一個攔截器。總有一個HandlerMapping是可以找到處理器的,最多也只找到一個處理器,所以這個攔截器總會被執行的。起到了總攔截器的作用。

如果是REST風格的URL,靜態資源也會被攔截。

  方案二, (近似) 總攔截器, 攔截匹配的URL。

Xml程式碼 複製程式碼 收藏程式碼

  1. <mvc:interceptors >     
  2.   <mvc:interceptor>     
  3.         <mvc:mapping path="/user/*" /> <!-- /user/*  -->     
  4.         <bean class="com.mvc.MyInteceptor"></bean>     
  5.     </mvc:interceptor>     
  6. </mvc:interceptors>    
  1. <mvc:interceptors >    
  2.   <mvc:interceptor>    
  3.         <mvc:mapping path="/user/*" /> <!-- /user/*  -->    
  4.         <bean class="com.mvc.MyInteceptor"></bean>    
  5.     </mvc:interceptor>    
  6. </mvc:interceptors>    

就是比 方案一多了一個URL匹配。

如果是REST風格的URL,靜態資源也會被攔截。

方案三,HandlerMappint上的攔截器。

如果是REST風格的URL,靜態資源就不會被攔截。因為我們精準的注入了攔截器。

Xml程式碼 複製程式碼 收藏程式碼

  1. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">        
  2.  <property name="interceptors">        
  3.      <list>        
  4.          <bean class="com.mvc.MyInteceptor"></bean>       
  5.      </list>        
  6.  </property>        
  7. </bean>   
  1. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">       
  2.  <property name="interceptors">       
  3.      <list>       
  4.          <bean class="com.mvc.MyInteceptor"></bean>      
  5.      </list>       
  6.  </property>       
  7. </bean>   

  如果使用了<mvc:annotation-driven />, 它會自動註冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter 這兩個bean,所以就沒有機會再給它注入interceptors屬性,就無法指定攔截器。

當然我們可以通過人工配置上面的兩個Bean,不使用 <mvc:annotation-driven />,就可以 給interceptors屬性 注入攔截器了。

其實我也不建議使用 <mvc:annotation-driven />,而建議手動寫詳細的配置檔案,來替代 <mvc:annotation-driven />,這就控制力就強了。

如何替換 <mvc:annotation-driven />?他到底做了什麼工作,請看,最後面的 十九節 <mvc:annotation-driven /> 到底做了什麼工作。

十一、如何實現全域性的異常處理?

在spring MVC的配置檔案中:

Xml程式碼 複製程式碼 收藏程式碼

  1. <!-- 總錯誤處理-->  
  2. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  3.     <property name="defaultErrorView">     
  4.         <value>/error/error</value>  
  5.     </property>  
  6.     <property name="defaultStatusCode">     
  7.         <value>500</value>  
  8.     </property>      
  9. <property name="warnLogCategory">     
  10.         <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>  
  11.     </property>      
  12. </bean>   
  1. <!-- 總錯誤處理-->  
  2. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  3.     <property name="defaultErrorView">    
  4.         <value>/error/error</value>  
  5.     </property>  
  6.     <property name="defaultStatusCode">    
  7.         <value>500</value>  
  8.     </property>     
  9. <property name="warnLogCategory">    
  10.         <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>  
  11.     </property>     
  12. </bean>   

這裡主要的類是SimpleMappingExceptionResolver類,和他的父類AbstractHandlerExceptionResolver類。

具體可以配置哪些屬性,我是通過檢視原始碼知道的。

你也可以實現HandlerExceptionResolver介面,寫一個自己的異常處理程式。spring的擴充套件性是很好的。

通過SimpleMappingExceptionResolver我們可以將不同的異常對映到不同的jsp頁面(通過exceptionMappings屬性的配置)。

同時我們也可以為所有的異常指定一個預設的異常提示頁面(通過defaultErrorView屬性的配置),如果所丟擲的異常在exceptionMappings中沒有對應的對映,則Spring將用此預設配置顯示異常資訊。

注意這裡配置的異常顯示介面均僅包括主檔名,至於檔案路徑和字尾已經在viewResolver中指定。如/error/error表示/error/error.jsp

顯示錯誤的jsp頁面:

Html程式碼 複製程式碼 收藏程式碼

  1. <%@ page language="java" contentType="text/html; charset=GBK"  
  2.     pageEncoding="GBK"%>  
  3. <%@ page import="java.lang.Exception"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=GBK">  
  8. <title>錯誤頁面</title>  
  9. </head>  
  10. <body>  
  11. <h1>出錯了</h1>  
  12. <%   
  13. Exception e = (Exception)request.getAttribute("exception");   
  14. out.print(e.getMessage());   
  15. %>  
  16. </body>  
  17. </html>  
  1. <%@ page language="java" contentType="text/html; charset=GBK"  
  2.     pageEncoding="GBK"%>  
  3. <%@ page import="java.lang.Exception"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=GBK">  
  8. <title>錯誤頁面</title>  
  9. </head>  
  10. <body>  
  11. <h1>出錯了</h1>  
  12. <%  
  13. Exception e = (Exception)request.getAttribute("exception");  
  14. out.print(e.getMessage());  
  15. %>  
  16. </body>  
  17. </html>  

其中一句:request.getAttribute("exception"),key是exception,也是在SimpleMappingExceptionResolver類預設指定的,是可能通過配置檔案修改這個值的,大家可以去看原始碼。

十二、如何把全域性異常記錄到日誌中?

在前的配置中,其中有一個屬性warnLogCategory,值是“SimpleMappingExceptionResolver類的全限定名”。我是在SimpleMappingExceptionResolver類父類AbstractHandlerExceptionResolver類中找到這個屬性的。檢視原始碼後得知:如果warnLogCategory不為空,spring就會使用apache的org.apache.commons.logging.Log日誌工具,記錄這個異常,級別是warn。

值:“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”,是“SimpleMappingExceptionResolver類的全限定名”。這個值不是隨便寫的。 因為我在log4j的配置檔案中還要加入log4j.logger.org.springframework.web.servlet.handler.SimpleMappingExceptionResolver=WARN,保證這個級別是warn的日誌一定會被記錄,即使log4j的根日誌級別是ERROR。

 十三、如何給spring3 MVC中的Action做JUnit單元測試?

 使用了spring3 MVC後,給action做單元測試變得很方便,我以前從來不給action寫單元測試的,現在可以根據情況寫一些了。

 不用給每個Action都寫單元測試吧,自己把握吧。

 JUnitActionBase類是所有JUnit的測試類的父類

Java程式碼 複製程式碼 收藏程式碼

  1. package test;   
  2. import javax.servlet.http.HttpServletRequest;   
  3. import javax.servlet.http.HttpServletResponse;   
  4. import org.junit.BeforeClass;   
  5. import org.springframework.mock.web.MockServletContext;   
  6. import org.springframework.web.context.WebApplicationContext;   
  7. import org.springframework.web.context.support.XmlWebApplicationContext;   
  8. import org.springframework.web.servlet.HandlerAdapter;   
  9. import org.springframework.web.servlet.HandlerExecutionChain;   
  10. import org.springframework.web.servlet.HandlerMapping;   
  11. import org.springframework.web.servlet.ModelAndView;   
  12. import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;   
  13. import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;   
  14. /**   
  15. * 說明: JUnit測試action時使用的基類  
  16. *   
  17. * @author  趙磊  
  18. * @version 建立時間:2011-2-2 下午10:27:03    
  19. */    
  20. public class JUnitActionBase {   
  21.     private static HandlerMapping handlerMapping;   
  22.     private static HandlerAdapter handlerAdapter;   
  23.     /**  
  24.      * 讀取spring3 MVC配置檔案  
  25.      */  
  26.     @BeforeClass  
  27.  public static void setUp() {   
  28.         if (handlerMapping == null) {   
  29.             String[] configs = { "file:src/springConfig/springMVC.xml" };   
  30.             XmlWebApplicationContext context = new XmlWebApplicationContext();   
  31.             context.setConfigLocations(configs);   
  32.             MockServletContext msc = new MockServletContext();   
  33.             context.setServletContext(msc);         context.refresh();   
  34.             msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);   
  35.             handlerMapping = (HandlerMapping) context   
  36.                     .getBean(DefaultAnnotationHandlerMapping.class);   
  37.             handlerAdapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);      
  38.         }   
  39.     }   
  40.     /**  
  41.      * 執行request物件請求的action  
  42.      *   
  43.      * @param request  
  44.      * @param response  
  45.      * @return  
  46.      * @throws Exception  
  47.      */  
  48.     public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)   
  49.  throws Exception {   
  50.         HandlerExecutionChain chain = handlerMapping.getHandler(request);   
  51.         final ModelAndView model = handlerAdapter.handle(request, response,   
  52.                 chain.getHandler());   
  53.         return model;   
  54.     }   
  55. }  
  1. package test;  
  2. import javax.servlet.http.HttpServletRequest;  
  3. import javax.servlet.http.HttpServletResponse;  
  4. import org.junit.BeforeClass;  
  5. import org.springframework.mock.web.MockServletContext;  
  6. import org.springframework.web.context.WebApplicationContext;  
  7. import org.springframework.web.context.support.XmlWebApplicationContext;  
  8. import org.springframework.web.servlet.HandlerAdapter;  
  9. import org.springframework.web.servlet.HandlerExecutionChain;  
  10. import org.springframework.web.servlet.HandlerMapping;  
  11. import org.springframework.web.servlet.ModelAndView;  
  12. import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;  
  13. import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;  
  14. /**  
  15. * 說明: JUnit測試action時使用的基類 
  16. *  
  17. * @author  趙磊 
  18. * @version 建立時間:2011-2-2 下午10:27:03   
  19. */   
  20. public class JUnitActionBase {  
  21.     private static HandlerMapping handlerMapping;  
  22.     private static HandlerAdapter handlerAdapter;  
  23.     /** 
  24.      * 讀取spring3 MVC配置檔案 
  25.      */  
  26.     @BeforeClass  
  27.  public static void setUp() {  
  28.         if (handlerMapping == null) {  
  29.             String[] configs = { "file:src/springConfig/springMVC.xml" };  
  30.             XmlWebApplicationContext context = new XmlWebApplicationContext();  
  31.             context.setConfigLocations(configs);  
  32.             MockServletContext msc = new MockServletContext();  
  33.             context.setServletContext(msc);         context.refresh();  
  34.             msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);  
  35.             handlerMapping = (HandlerMapping) context  
  36.                     .getBean(DefaultAnnotationHandlerMapping.class);  
  37.             handlerAdapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);     
  38.         }  
  39.     }  
  40.     /** 
  41.      * 執行request物件請求的action 
  42.      *  
  43.      * @param request 
  44.      * @param response 
  45.      * @return 
  46.      * @throws Exception 
  47.      */  
  48.     public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)  
  49.  throws Exception {  
  50.         HandlerExecutionChain chain = handlerMapping.getHandler(request);  
  51.         final ModelAndView model = handlerAdapter.handle(request, response,  
  52.                 chain.getHandler());  
  53.         return model;  
  54.     }  
  55. }  

這是個JUnit測試類,我們可以new Request物件,來參與測試,太方便了。給request指定訪問的URL,就可以請求目標Action了。

Java程式碼 複製程式碼 收藏程式碼

  1. package test.com.app.user;   
  2. import org.junit.Assert;   
  3. import org.junit.Test;   
  4. import org.springframework.mock.web.MockHttpServletRequest;   
  5. import org.springframework.mock.web.MockHttpServletResponse;   
  6. import org.springframework.web.servlet.ModelAndView;   
  7. import test.JUnitActionBase;   
  8. /**   
  9. * 說明: 測試OrderAction的例子  
  10. *   
  11. * @author  趙磊   
  12. * @version 建立時間:2011-2-2 下午10:26:55    
  13. */    
  14. public class TestOrderAction extends JUnitActionBase {   
  15.     @Test  
  16.     public void testAdd() throws Exception {   
  17.     MockHttpServletRequest request = new MockHttpServletRequest();   
  18.         MockHttpServletResponse response = new MockHttpServletResponse();   
  19.         request.setServletPath("/order/add");   
  20.         request.addParameter("id", "1002");   
  21.         request.addParameter("date", "2010-12-30");   
  22.         request.setMethod("POST");   
  23.         // 執行URI對應的action   
  24.         final ModelAndView mav = this.excuteAction(request, response);   
  25.         // Assert logic   
  26.         Assert.assertEquals("order/add", mav.getViewName());   
  27.         String msg=(String)request.getAttribute("msg");   
  28.         System.out.println(msg);   
  29.     }   
  30. }  
  1. package test.com.app.user;  
  2. import org.junit.Assert;  
  3. import org.junit.Test;  
  4. import org.springframework.mock.web.MockHttpServletRequest;  
  5. import org.springframework.mock.web.MockHttpServletResponse;  
  6. import org.springframework.web.servlet.ModelAndView;  
  7. import test.JUnitActionBase;  
  8. /**  
  9. * 說明: 測試OrderAction的例子 
  10. *  
  11. * @author  趙磊  
  12. * @version 建立時間:2011-2-2 下午10:26:55   
  13. */   
  14. public class TestOrderAction extends JUnitActionBase {  
  15.     @Test  
  16.     public void testAdd() throws Exception {  
  17.     MockHttpServletRequest request = new MockHttpServletRequest();  
  18.         MockHttpServletResponse response = new MockHttpServletResponse();  
  19.         request.setServletPath("/order/add");  
  20.         request.addParameter("id", "1002");  
  21.         request.addParameter("date", "2010-12-30");  
  22.         request.setMethod("POST");  
  23.         // 執行URI對應的action  
  24.         final ModelAndView mav = this.excuteAction(request, response);  
  25.         // Assert logic  
  26.         Assert.assertEquals("order/add", mav.getViewName());  
  27.         String msg=(String)request.getAttribute("msg");  
  28.         System.out.println(msg);  
  29.     }  
  30. }  

 需要說明一下 :由於當前最想版本的Spring(Test) 3.0.5還不支援@ContextConfiguration的註解式context file注入,所以還需要寫個setUp處理下,否則類似於Tiles的載入過程會有錯誤,因為沒有ServletContext。3.1的版本應該有更好的解決方案,

 十四、轉發與重定向

可以通過redirect/forward:url方式轉到另一個Action進行連續的處理。

可以通過redirect:url 防止表單重複提交 。

寫法如下:

return "forward:/order/add";

return "redirect:/index.jsp";

帶引數重定向--RedirectAttributes

使用者儲存或修改後,為了防止使用者重新整理瀏覽器(F5)導致表單重複提交,一般在儲