夾
一個、前言
兩、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性能都很好。
Spring3 MVC的長處:
1、Spring3 MVC使用簡單,學習成本低。學習難度小于Struts2,Struts2用不上的多餘功能太多。呵呵,當然這不是決定因素。
2、Spring3 MVC非常easy就能夠寫出性能優秀的程式,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接口的實作類的不同而不同。
先來看第一個樣例:
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
</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。
第二個樣例:
<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*:/springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<url-pattern>/</url-pattern>
</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監聽器的。例如以下
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</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 version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 自己主動掃描的包名 -->
<context:component-scan base-package="com.app,com.core,JUnit4" ></context:component-scan>
<!-- 預設的注解映射的支援 -->
<mvc:annotation-driven />
<!-- 視圖解釋類 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/><!--可為空,友善實作自已的根據擴充名來選擇視圖解釋類的邏輯 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
<!-- 攔截器 -->
<mvc:interceptors>
<bean class="com.core.mvc.MyInteceptor" />
</mvc:interceptors>
<!-- 對靜态資源檔案的訪問 方案一 (二選一) -->
<mvc:default-servlet-handler/>
<!-- 對靜态資源檔案的訪問 方案二 (二選一)-->
<mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>
<mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>
<mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>
</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來處理靜态檔案
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
要配置多個,每種檔案配置一個
要寫在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 。 用法:
<!-- 對靜态資源檔案的訪問 -->
<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/>
<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。
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> </bean>
但前面我們配置了<mvc:annotation-driven />,他會自己主動注冊這個bean,就不需要我們顯示的注冊這個bean了。
以上都能夠注入interceptors,實作權限控制等前置工作。
我們使用第2種,基于注解來使用spring MVC
并在action類上使用:
@Controller
@RequestMapping("/user")
九、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是下一個攔截器。
十、怎樣使用攔截器?
自己定義一個攔截器,要實作HandlerInterceptor接口:
public class MyInteceptor implements HandlerInterceptor {
略。
。。
}
Spring MVC并沒有總的攔截器,不能對全部的請求進行前後攔截。
Spring MVC的攔截器。是屬于HandlerMapping級别的,能夠有多個HandlerMapping 。每一個HandlerMapping能夠有自己的攔截器。
當一個請求按Order值從小到大,順序運作HandlerMapping接口的實作類時。哪一個先有傳回,那就能夠結束了。後面的HandlerMapping就不走了,本道工序就完畢了。就轉到下一道工序了。
攔截器會在什麼時候運作呢? 一個請求交給一個HandlerMapping時,這個HandlerMapping先找有沒有處理器來處理這個請求,怎樣找到了。就運作攔截器。運作完攔截後,交給目标處理器。
假設沒有找到處理器,那麼這個攔截器就不會被運作。
在spring MVC的配置檔案裡配置有三種方法:
方案一,(近似)總攔截器,攔截全部url
<mvc:interceptors>
<bean class="com.app.mvc.MyInteceptor" />
</mvc:interceptors>
為什麼叫“近似”,前面說了,Spring沒有總的攔截器。
<mvc:interceptors/>會為每個HandlerMapping。注入一個攔截器。總有一個HandlerMapping是能夠找到處理器的,最多也僅僅找到一個處理器。是以這個攔截器總會被運作的。
起到了總攔截器的作用。
假設是REST風格的URL,靜态資源也會被攔截。
方案二。(近似)總攔截器,攔截比對的URL。
<mvc:interceptors >
<mvc:interceptor>
<mvc:mapping path="/user/*" /> <!-- /user/* -->
<bean class="com.mvc.MyInteceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
就是比方案一多了一個URL比對。
假設是REST風格的URL。靜态資源也會被攔截。
方案三,HandlerMappint上的攔截器。
假設是REST風格的URL,靜态資源就不會被攔截。由于我們精準的注入了攔截器。
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<bean class="com.mvc.MyInteceptor"></bean>
</list>
</property>
</bean>
假設使用了<mvc:annotation-driven />, 它會自己主動注冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter 這兩個bean,是以就沒有機會再給它注入interceptors屬性,就無法指定攔截器。
當然我們能夠通過人工配置上面的兩個Bean。不使用<mvc:annotation-driven />,就能夠給interceptors屬性注入攔截器了。
事實上我也不建議使用<mvc:annotation-driven />。而建議手動寫具體的配置檔案,來替代<mvc:annotation-driven />。這就控制力就強了。
十一、怎樣實作全局的異常處理?
在spring MVC的配置檔案裡:
<!-- 總錯誤處理-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView">
<value>/error/error</value>
</property>
<property name="defaultStatusCode">
<value>500</value>
</property>
<property name="warnLogCategory">
<value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>
這裡基本的類是SimpleMappingExceptionResolver類。和他的父類AbstractHandlerExceptionResolver類。
詳細能夠配置哪些屬性。我是通過檢視源代碼知道的。
你也能夠實作HandlerExceptionResolver接口。寫一個自己的異常處理程式。spring的擴充性是非常好的。
通過SimpleMappingExceptionResolver我們能夠将不同的異常映射到不同的jsp頁面(通過exceptionMappings屬性的配置)。
同一時候我們也能夠為全部的異常指定一個預設的異常提示頁面(通過defaultErrorView屬性的配置)。假設所抛出的異常在exceptionMappings中沒有相應的映射。則Spring将用此預設配置顯示異常資訊。
注意這裡配置的異常顯示界面均僅包含主檔案名稱。至于檔案路徑和字尾已經在viewResolver中指定。
如/error/error表示/error/error.jsp
顯示錯誤的jsp頁面:
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ page import="java.lang.Exception"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>錯誤頁面</title>
</head>
<body>
<h1>出錯了</h1>
<%
Exception e = (Exception)request.getAttribute("exception");
out.print(e.getMessage());
%>
</body>
</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的測試類的父類
package test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.BeforeClass;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;
/**
* 說明: JUnit測試action時使用的基類
*
* @author 趙磊
* @version 建立時間:2011-2-2 下午10:27:03
*/
public class JUnitActionBase {
private static HandlerMapping handlerMapping;
private static HandlerAdapter handlerAdapter;
/**
* 讀取spring3 MVC配置檔案
*/
@BeforeClass
public static void setUp() {
if (handlerMapping == null) {
String[] configs = { "file:src/springConfig/springMVC.xml" };
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocations(configs);
MockServletContext msc = new MockServletContext();
context.setServletContext(msc); context.refresh();
msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
handlerMapping = (HandlerMapping) context
.getBean(DefaultAnnotationHandlerMapping.class);
handlerAdapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);
}
}
* 運作request對象請求的action
*
* @param request
* @param response
* @return
* @throws Exception
public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)
throws Exception {
HandlerExecutionChain chain = handlerMapping.getHandler(request);
final ModelAndView model = handlerAdapter.handle(request, response,
chain.getHandler());
return model;
}
這是個JUnit測試類,我們能夠new Request對象,來參與測試。太友善了。
給request指定訪問的URL,就能夠請求目标Action了。
package test.com.app.user;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import test.JUnitActionBase;
* 說明: 測試OrderAction的樣例
* @author 趙磊
* @version 建立時間:2011-2-2 下午10:26:55
public class TestOrderAction extends JUnitActionBase {
@Test
public void testAdd() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath("/order/add");
request.addParameter("id", "1002");
request.addParameter("date", "2010-12-30");
request.setMethod("POST");
// 運作URI相應的action
final ModelAndView mav = this.excuteAction(request, response);
// Assert logic
Assert.assertEquals("order/add", mav.getViewName());
String msg=(String)request.getAttribute("msg");
System.out.println(msg);
須要說明一下 :由于目前最想版本号的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)導緻表單重複送出。一般在儲存或改動操作之後會redirect到一個結果頁面(不是forward),同一時候攜帶參數,如操作成功的提示資訊。由于是Redirect,Request裡的attribute不會傳遞過去。Spring在3.1才提供了這個能力--RedirectAttributes。 重複按F5。操作成功的提示資訊也不會再次出來(總共僅僅出現一次),效果非常理想。
public String save(@ModelAttribute("group") Group group, RedirectAttributes redirectAttributes) {
accountManager.saveGroup(group);
redirectAttributes.addFlashAttribute("message", "操作成功");
return "redirect:/account/group/";
十五、處理ajax請求
jackson-core-asl-1.7.2.jar
jackson-mapper-asl-1.7.2.jar
2、spring的配置檔案裡要有這一行,才幹使用到spring内置支援的json轉換。
假設你手工把POJO轉成json就能夠不需要使用spring内置支援的json轉換。
<mvc:annotation-driven />
3、使用@ResponseBody注解
/**
* ajax測試
* http://127.0.0.1/mvc/order/ajax
*/
@RequestMapping("/ajax")
@ResponseBody
public Object ajax(HttpServletRequest request){
List<String> list=new ArrayList<String>();
list.add("電視");
nbsp; list.add("洗衣機");
list.add("冰箱");
list.add("電腦");
list.add("汽車");
list.add("空調");
list.add("自行車");
list.add("飲水機");
list.add("熱水器");
return list;
十六、關于寫幾個配置檔案的說明
我看到有的人把配置檔案寫兩份:
一個是原有的applicationContext.xml,這個檔案從spring2.0-2.5時一直在使用。
别一個是新加的spring MVC的配置檔案。
事實上這兩個檔案是能夠寫成一個檔案的。springMVC相關的配置,資料源,事務相關配置能夠都寫再一個配置檔案裡。
本樣例中僅僅使用了一個spring配置檔案叫“springMVC.xml”。
就不要再多配置一個applicationContext.xml檔案了。
web.xml檔案裡也不要再配置org.springframework.web.context.ContextLoaderListener的listener了。
寫兩個配置檔案一般就會導緻掃描兩次,一定要精确控制掃描的包名。做到不反複掃描。
寫兩個配置檔案還出現事務不好使的現象,是當把@Transactional寫有Action層時出現的。
是由于父子上下文的原因。請參看前的 第五節 父子上下文,裡面有說明 。原因是父上下文不能訪問子上下文。
十七、怎樣取得Spring管理的bean(請用第3種方法)
1、servlet方式載入時。
【web.xml】
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
spring容器放在ServletContext中的key是org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC
注意後面的springMVC,是你的servlet-name配置的值,注意适時改動。
ServletContext sc=略
WebApplicationContext attr = (WebApplicationContext)sc.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.springMVC");
2、listener方式載入時:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
【jsp/servlet】能夠這樣取得
ServletContext context = getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(context);
3、通用的方法來了,神器啊,前的 1、2兩種方法并不通用。能夠抛棄了。
在配置檔案裡增加:
<!-- 用于持有ApplicationContext,能夠使用SpringContextHolder.getBean('xxxx')的靜态方法得到spring bean對象 -->
<bean class="com.xxxxx.SpringContextHolder" lazy-init="false" />
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
* 以靜态變量儲存Spring ApplicationContext, 可在不論什麼代碼不論什麼地方不論什麼時候中取出ApplicaitonContext.
*
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
* 實作ApplicationContextAware接口的context注入函數, 将其存入靜态變量.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext; // NOSONAR
* 取得存儲在靜态變量中的ApplicationContext.
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
* 從靜态變量ApplicationContext中取得Bean, 自己主動轉型為所指派對象的類型.
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
public static <T> T getBean(Class<T> clazz) {
return (T) applicationContext.getBeansOfType(clazz);
* 清除applicationContext靜态變量.
public static void cleanApplicationContext() {
applicationContext = null;
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder");
十八、多視圖控制器
當有jsp,flt (模闆)等多種頁面生成展示方式時,spring預設使用的是“視圖解析器鍊”。 真是一個鍊,是以性能不好,spring會在“視圖解析器鍊”中順序的查找,直到找到相應的 “視圖解析器” 。jsp視圖解析器一定要寫在最後面,由于一旦調用jsp,就向浏覽器發出資料了,Spring就沒有機會再嘗試下一個了。
是以自己寫一個"多視圖解析器"。依靠擴充名來區分,可一次準确的選中一個 視圖解析器,提高性能(會有多少提高呢?沒測試過).
以下的樣例支援jsp,flt (模闆)兩種頁面生成展示方式,你中以自己加入。支援很多其它。
<!-- 多視圖處理器 -->
<bean class="com.xxx.core.web.MixedViewResolver">
<property name="resolvers">
<map>
<entry key="jsp">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
</bean>
</entry>
<entry key="ftl">
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="contentType" value="text/html;charset=UTF-8"></property>
<!-- 宏指令的支援 -->
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
<property name="requestContextAttribute" value="rc"></property>
</map>
</bean>
<!-- freemarker config -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">5</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
</props>
</property>
</bean>
import java.util.Locale;
import java.util.Map;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
* 說明: 多視圖處理器
* @version 建立時間:2011-8-19 上午09:41:09
public class MixedViewResolver implements ViewResolver{
private Map<String,ViewResolver> resolvers;
public void setResolvers(Map<String, ViewResolver> resolvers) {
this.resolvers = resolvers;
public View resolveViewName(String viewName,Locale locale) throws Exception{
int n=viewName.lastIndexOf(".");
if(n!=-1){
//取出擴充名
String suffix=viewName.substring(n+1);
//取出相應的ViewResolver
ViewResolver resolver=resolvers.get(suffix);
if(resolver==null){
throw new RuntimeException("No ViewResolver for "+suffix);
}
return resolver.resolveViewName(viewName, locale);
}else{
ViewResolver resolver=resolvers.get("jsp");
十九、 <mvc:annotation-driven /> 究竟做了什麼工作
一句<mvc:annotation-driven />實際做了下面工作:(不包含加入自定義的攔截器)
我們了解這些之後,對Spring3 MVC的控制力就更強大了,想改哪就改哪裡。
<!-- 注解請求映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="logNDCInteceptor"/> <!-- 日志攔截器。這是你自己定義的攔截器 -->
<ref bean="myRequestHelperInteceptor"/> <!-- RequestHelper攔截器,這是你自己定義的攔截器-->
<ref bean="myPermissionsInteceptor"/> <!-- 權限攔截器,這是你自己定義的攔截器-->
<ref bean="myUserInfoInteceptor"/> <!-- 使用者資訊攔截器。這是你自己定義的攔截器-->
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<ref bean="byteArray_hmc" />
<ref bean="string_hmc" />
<ref bean="resource_hmc" />
<ref bean="source_hmc" />
<ref bean="xmlAwareForm_hmc" />
<ref bean="jaxb2RootElement_hmc" />
<ref bean="jackson_hmc" />
</list>
</property>
</bean>
<bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /><!-- 處理.. -->
<bean id="string_hmc" class="org.springframework.http.converter.StringHttpMessageConverter" /><!-- 處理.. -->
<bean id="resource_hmc" class="org.springframework.http.converter.ResourceHttpMessageConverter" /><!-- 處理.. -->
<bean id="source_hmc" class="org.springframework.http.converter.xml.SourceHttpMessageConverter" /><!-- 處理.. -->
<bean id="xmlAwareForm_hmc" class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" /><!-- 處理.. -->
<bean id="jaxb2RootElement_hmc" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /><!-- 處理.. -->
<bean id="jackson_hmc" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /><!-- 處理json-->
版權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
本文轉自mfrbuaa部落格園部落格,原文連結:http://www.cnblogs.com/mfrbuaa/p/4629950.html,如需轉載請自行聯系原作者