Spring MVC Dispatcherservlet Detailed interceptor and filter differences

Source: Internet
Author: User

First, let's look at the features and implementations of Spring MVC Interceptor:

Http://wenku.baidu.com/link?url=Mw3GaUhCRMhUFjU8iIDhObQpDcbmmRy_ Ipeumazg0ppnbmwqfutlp9kspupppeysf6enhblyfewrbjqmq8blwkqz_7msdhgqtvl32fpxcmm

The Interceptor interceptor in SPRINGMVC is also very important and useful, and its main function is to intercept the user's request and do the corresponding processing, other functions such as through it to verify the permissions, or to determine whether the user login, logging, or restricting time-point access.

The interceptor interception request in SPRINGMVC is implemented through Handlerinterceptor. Defining a interceptor in SPRINGMVC is very simple, mainly in two ways, the first way is to define the Interceptor class to implement the spring Handlerinterceptor interface, Or this class inherits the class that implements the Handlerinterceptor interface, such as the abstract class that spring has provided to implement the Handlerinterceptor interface Handlerinterceptoradapter The second way is to implement the spring Webrequestinterceptor interface, or to inherit the class that implements the Webrequestinterceptor.

There are three methods defined in the Handlerinterceptor interface, and we are using these three methods to intercept the user's request.

   (1) prehandle (httpservletrequest request, httpservletresponse response, Object handle) method. The method is called before the request is processed. Interceptor in SPRINGMVC is a chained invocation, where multiple interceptor can exist in one application or in one request. Each interceptor call is executed sequentially according to its declaration order, and the first execution is the Prehandle method in interceptor, so you can do some pre-initialization operations in this method or a preprocessing of the current request. You can also make some judgments in this method to determine whether the request is going to go on. The return value of the method is a Boolean of type bool, and when it returns to false, it means that the request ends and that subsequent interceptor and controllers are no longer executed, and the next interceptor is resumed when the return value is True Prehandle method, which is the Controller method that invokes the current request if it is already the last interceptor.

(2) Posthandle (HttpServletRequest request, httpservletresponse response, Object handle, Modelandview Modelandview) method, By the interpretation of the Prehandle method, we know that this method, including the Aftercompletion method to be mentioned later, can only be called if the return value of the Prehandle method of the currently owned interceptor is true. The Posthandle method, as the name implies, is executed after the current request is processed, that is, after the controller method call, but it is called before the view returns to render Dispatcherservlet. So we can manipulate the Modelandview object after controller processing in this method. The Posthandle method is called in the opposite direction to Prehandle, which means that the Posthandle method of the declared interceptor is executed later, which is somewhat different from the Struts2 execution in interceptor. Struts2 inside the Interceptor execution process is also chained, but in Struts2 need to manually invoke the Actioninvocation invoke method to trigger the next interceptor or action call, Then the contents of each interceptor before the Invoke method call are executed in the order of Declaration, and the content after the Invoke method is reversed.

(3) Aftercompletion (HttpServletRequest request, httpservletresponse response, Object handle, Exception ex) method, This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true to execute. As the name implies, the method executes after the entire request is finished, that is, after Dispatcherservlet renders the corresponding view. The main function of this method is to perform resource cleanup work. Interception of our system logs in this method, the relevant parameters of the log can be recorded and the execution of the detection method is performed.

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

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

 Public InterfaceHandlerinterceptorworkflowInterfacethat allows forCustomized handler execution chains. Applications can register any number of existing or custom interceptors forcertain groups of handlers, to add common preprocessing behavior without needing to modify each handler Implementatio N.a Handlerinterceptor gets called before the appropriate handleradapter triggers the execution of the handler itself. This mechanism can used forA large field of preprocessing aspects, e.g. forAuthorization checks, or common handler behavior like locale or theme changes.Its main purpose are to allow for Factoring out repetitive handler code. In an async processing scenario, the handler is executed in a separate thread whileThe main thread exits without rendering or invoking the Posthandle and aftercompletion callbacks. When concurrent handler execution completes, the request was dispatched back on order to proceed with rendering the Model A nd all methods of Thiscontract is invoked again. For further options and details see Org.springframework.web.servlet.AsyncHandlerInterceptorTypically an Interceptor Chain is defined per handlermapping beans, sharing its granularity. To is able to apply a certain interceptor chain to a group of handlers, one needs to map the desired handlers via one Hand Lermapping Bean.  The interceptors themselves is 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 Servlet2.3 Filter, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the Executio N of the handler itself, and custom post-processing. Filters is more powerful, forExample they allow forexchanging the request and response objects that is 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 is candidates forHandlerinterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited forRequest content and view content handling, like multipart forms and GZIP compression. This typically shows if one needs to maps the filter to certain content types (e.g. images), or to all requests.

 Public InterfaceFilterA Filter is an object, performs filtering tasks on either, the request to a resource (a servlet orStaticcontent), or on the response from a resource, or both. Filters perform filtering in the DoFilter method. Every Filter have access to a Filterconfig object from which it can obtain its initialization parameters, a reference to th e ServletContext which it can use, forexample, to load resources needed forfiltering tasks. Filters is configured in the deployment descriptor of a Web applicationexamples that has been identified for  ThisDesign is1) authentication Filters2) Logging and Auditing Filters3) Image Conversion Filters4) Data compression Filters5) Encryption Filters6) tokenizing Filters7) Filters that trigger resource access events8) xsl/T Filters9) Mime-type Chain Filter

The concepts of interceptor and filter are similar, but the main differences are:

Web application filtering requests, using only Web applications;

Interceptor applies to specific group of handler, can be Web application can also enterprise application;

Data found from Google: http://www.linkedin.com/groups/what-is-difference-between-interceptor-3983267.S.5844715100472107010

Filter is used only in the Web applications whereas interceptor can be used with the 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 is 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 is defined.

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

There is 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 is configured whether to execute or not by means of excludemethods or includemethods

Spring MVC Dispatcherservlet Detailed interceptor and filter differences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.