The difference between interceptor and filter in spring mvc DispatcherServlet detailed explanation

http://www.cnblogs.com/davidwang456/p/4108355.html

 

 

First, let's take a look at the function and implementation of spring mvc Interceptor:

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

The Interceptor interceptor in SpringMVC is also very important and useful. Its main function is to intercept user requests and process them accordingly. Other functions such as permission verification through it, or to determine whether the user is logged in and logging. , or restrict point-in-time access.

The Interceptor in SpringMVC intercepts requests through HandlerInterceptor. It is very simple to define an Interceptor in SpringMVC. There are two main ways. The first way is that the Interceptor class to be defined should implement Spring's HandlerInterceptor interface, or this class should inherit a class that implements the HandlerInterceptor interface, such as the one already provided by Spring. The abstract class HandlerInterceptorAdapter that implements the HandlerInterceptor interface; the second way is to implement Spring's WebRequestInterceptor interface, or inherit a class that implements WebRequestInterceptor.

The HandlerInterceptor interface defines three methods, through which we intercept and process user requests.

   (1) preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) method. This method will be called before the request is processed. The Interceptor in SpringMVC is called in a chain, and multiple Interceptors can exist at the same time in an application or in a request. Each Interceptor call will be executed in sequence according to its declaration order, and the preHandle method in the Interceptor is executed first, so you can perform some pre-initialization operations in this method or a preprocessing of the current request, and also Some judgment can be made in this method to decide whether the request should proceed. The return value of this method is of Boolean type. When it returns false, it means that the request is over, and subsequent Interceptors and Controllers will not be executed; when the return value is true, it will continue to call the preHandle method of the next Interceptor. , if it is the last Interceptor, it will call the Controller method of the current request.

   (2) postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) method, from the explanation of the preHandle method, we know that this method, including the afterCompletion method to be mentioned later, can only be the return of the preHandle method of the currently affiliated Interceptor It can only be called when the value is true. The postHandle method, as the name implies, is executed after the current request is processed, that is, after the Controller method is called, but it will be called before the DispatcherServlet returns and renders the view, so we can operate on the ModelAndView object processed by the Controller in this method. The direction in which the postHandle method is called is opposite to that of preHandle, that is to say, the postHandle method of the Interceptor declared first will be executed later, which is somewhat similar to the execution process of the Interceptor in Struts2. The execution process of the Interceptor in Struts2 is also chained, but in Struts2, the invoke method of ActionInvocation needs to be manually called to trigger the call to the next Interceptor or Action, and then the content of each Interceptor before the invoke method is called according to The declarations are executed in order, and the content after the invoke method is reversed.

   (3) AfterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) method, this method is also executed only when the return value of the current corresponding Interceptor's preHandle method is true. As the name suggests, this method will be executed after the entire request is over, that is, after the DispatcherServlet has rendered the corresponding view. The main function of this method is to perform resource cleanup work. In this method, the interception of our system log can record the relevant parameters of the log and detect the execution of the method.

 

Here, we have a question: what is the difference between interceptors and filters?

First, let's take a look at how the official explanation is:

复制代码
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

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326839493&siteId=291194637