1. 程式人生 > >spring mvc DispatcherServlet詳解之interceptor和filter的區別

spring mvc DispatcherServlet詳解之interceptor和filter的區別

首先我們看一下spring mvc Interceptor的功能及實現:

http://wenku.baidu.com/link?url=Mw3GaUhCRMhUFjU8iIDhObQpDcbmmRy_IPeumazg0ppnbmwqFUtLp9kSpuPPpeysf6EnHBLYFeWrbjqMq8BlWKQz_7MSDhGQTVl32fpxCMm

SpringMVC 中的Interceptor 攔截器也是相當重要和相當有用的,它的主要作用是攔截使用者的請求並進行相應的處理,其他的作用比如通過它來進行許可權驗證,或者是來判斷使用者是否登陸,日誌記錄,或者限制時間點訪問。

SpringMVC 中的Interceptor 攔截請求是通過HandlerInterceptor 來實現的。在SpringMVC 中定義一個Interceptor 非常簡單,主要有兩種方式,第一種方式是要定義的Interceptor類要實現了Spring 的HandlerInterceptor 介面,或者是這個類繼承實現了HandlerInterceptor 介面的類,比如Spring 已經提供的實現了HandlerInterceptor 介面的抽象類HandlerInterceptorAdapter ;第二種方式是實現Spring的WebRequestInterceptor介面,或者是繼承實現了WebRequestInterceptor的類。

HandlerInterceptor 介面中定義了三個方法,我們就是通過這三個方法來對使用者的請求進行攔截處理的。

   (1 )preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) 方法。該方法將在請求處理之前進行呼叫。SpringMVC 中的Interceptor 是鏈式的呼叫的,在一個應用中或者說是在一個請求中可以同時存在多個Interceptor 。每個Interceptor 的呼叫會依據它的宣告順序依次執行,而且最先執行的都是Interceptor 中的preHandle 方法,所以可以在這個方法中進行一些前置初始化操作或者是對當前請求的一個預處理,也可以在這個方法中進行一些判斷來決定請求是否要繼續進行下去。該方法的返回值是布林值Boolean 型別的,當它返回為false 時,表示請求結束,後續的Interceptor 和Controller 都不會再執行;當返回值為true 時就會繼續呼叫下一個Interceptor 的preHandle 方法,如果已經是最後一個Interceptor 的時候就會是呼叫當前請求的Controller 方法。

   (2 )postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) 方法,由preHandle 方法的解釋我們知道這個方法包括後面要說到的afterCompletion 方法都只能是在當前所屬的Interceptor 的preHandle 方法的返回值為true 時才能被呼叫。postHandle 方法,顧名思義就是在當前請求進行處理之後,也就是Controller 方法呼叫之後執行,但是它會在DispatcherServlet 進行檢視返回渲染之前被呼叫,所以我們可以在這個方法中對Controller 處理之後的ModelAndView 物件進行操作。postHandle 方法被呼叫的方向跟preHandle 是相反的,也就是說先宣告的Interceptor 的postHandle 方法反而會後執行,這和Struts2 裡面的Interceptor 的執行過程有點型別。Struts2 裡面的Interceptor 的執行過程也是鏈式的,只是在Struts2 裡面需要手動呼叫ActionInvocation 的invoke 方法來觸發對下一個Interceptor 或者是Action 的呼叫,然後每一個Interceptor 中在invoke 方法呼叫之前的內容都是按照宣告順序執行的,而invoke 方法之後的內容就是反向的。

   (3 )afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) 方法,該方法也是需要當前對應的Interceptor 的preHandle 方法的返回值為true 時才會執行。顧名思義,該方法將在整個請求結束之後,也就是在DispatcherServlet 渲染了對應的檢視之後執行。這個方法的主要作用是用於進行資源清理工作的。 我們的系統日誌的攔截在這個方法中,可以記錄日誌的相關的引數,檢測方法的執行。

在這裡,我們就有一個疑問了:攔截器和過濾器到底有什麼不同呢?

首先,我們看一下官方是怎麼解釋的:

複製程式碼
public interface HandlerInterceptor
Workflow interface that allows for customized handler execution chains. Applications can register any number of existing or custom interceptors for certain groups of handlers, to add common preprocessing behavior without needing to modify each handler implementation.
A HandlerInterceptor gets called before the appropriate HandlerAdapter triggers the execution of the handler itself. This mechanism can be used for a large field of preprocessing aspects, e.g. for authorization checks, or common handler behavior like locale or theme changes. Its main purpose is to allow for factoring out repetitive handler code.

In an async processing scenario, the handler may be executed in a separate thread while the main thread exits without rendering or invoking the postHandle and afterCompletion callbacks. When concurrent handler execution completes, the request is dispatched back in order to proceed with rendering the model and all methods of this contract are invoked again. For further options and details see org.springframework.web.servlet.AsyncHandlerInterceptor

Typically an interceptor chain is defined per HandlerMapping bean, sharing its granularity. To be able to apply a certain interceptor chain to a group of handlers, one needs to map the desired handlers via one HandlerMapping bean. The interceptors themselves are defined as beans in the application context, referenced by the mapping bean definition via its "interceptors" property (in XML: a <list> of <ref>).

HandlerInterceptor is basically similar to a Servlet 2.3 Filter, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context.

As a basic guideline, fine-grained handler-related preprocessing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
複製程式碼 複製程式碼
public interface Filter
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. 

Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.

Filters are configured in the deployment descriptor of a web application

Examples that have been identified for this design are
1) Authentication Filters 
2) Logging and Auditing Filters 
3) Image conversion Filters 
4) Data compression Filters 
5) Encryption Filters 
6) Tokenizing Filters 
7) Filters that trigger resource access events 
8) XSL/T filters 
9) Mime-type chain Filter 
複製程式碼

interceptor 和filter的概念相似,但主要不同點有:

web應用的過濾請求,僅使用web應用;

interceptor應用於特定組別的handler,可以web應用也可以企業應用;

從google找到的資料:http://www.linkedin.com/groups/what-is-difference-between-interceptor-3983267.S.5844715100472107010

Filter is used only in web applications whereas interceptor can be used with web as well as enterprise applications. Life cycle methods of both, also differs. The Interceptor stack fires on requests in a configured package while filters only apply to their mapped URL's. 

Example: 

A Servlet Filter is used in the web layer only, you can't use it outside of a 
web context. Interceptors can be used anywhere. 

The interceptor stack fires on every request. 
Filters only apply to the urls for which they are defined. 

Filters can be used when you want to modify any request or response parameters like headers. For example you would like to add a response header "Powered By Surya" to each generated response. Instead of adding this header in each resource method you would use a response filter to add this header. 

There are filters on the server side and the client side. 

In Summary: 

Filters: 

(1)Based on Servlet Specification 
(2)Executes on the pattern matches on the request. 
(3) Not configurable method calls. 


Interceptors: 
(1)Based on Struts2. 
(2)Executes for all the request qualifies for a front controller( A Servlet filter ).And can be configured to execute additional interceptor for a particular action execution. 
(3)Methods in the Interceptors can be configured whether to execute or not by means of excludemethods or includeMethods