SPRINGMVC Interceptor Use and principle understanding

Source: Internet
Author: User

Similar to Struts2, the SPRINGMVC's interceptor is the main function of the server to actually handle the request before and after some related operations. such as initialization of resources, permissions monitoring, Session settings, menu acquisition, resource cleanup, and so on.

Steps:

1. Defining interceptors

Custom interceptors generally inherit from Handlerinterceptoradapter or implement the Handlerinterceptor interface. Implementing an interface requires implementing the corresponding 3 method, and inheriting the parent class requires only implementing the required method. Prehandle,posthandle,aftercompletion

 Public classMyinterceptorextendsHandlerinterceptoradapter {@Override Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsException {/** * Prehandle method is used for processor interception, as the name implies, the method will be called before the controller processing, * SPRINGMVC in the Interceptor interceptor is chained, you can have multiple interceptor     , * then SPRINGMVC will execute one after the other according to the order of the Declaration, * and all prehandle methods in interceptor will be called before the Controller method call.    * SPRINGMVC This interceptor chain structure can also be interrupted, * This mode of interruption is to make the return value of Prehandle is false, when the return value of Prehandle is false, the entire request is over. This way, if the return is false, the general situation needs to redirect or forward to other pages, using the request forwarding or response redirection */} @Override Public voidPosthandle (HttpServletRequest request, httpservletresponse response, Object handler, Modelandview Modelandview)throwsException {/** * This method will only be executed if the current interceptor Prehandle method returns a value of true. Posthandle is used for processor interception, and its execution time is after the processor is processed, that is, after the controller's method call, but it will be executed before rendering the view Dispatcherservlet. This means that you can operate on the Modelandview in this method. The chain structure of this method is the opposite of the normal access direction, that is to say the first declaration of the Interceptor Interceptor this method will be called later, which is a bit like the execution process of the interceptor inside the STRUTS2, Just Struts2 inside the Intercept method to manually invoke the Actioninvocation invoke method, The Invoke method for calling Actioninvocation in Struts2 is to call the next interceptor or call the action, and then the content to be called before Interceptor is written before invoking invoke.     The content to be called after Interceptor is written after invoking the Invoke method. */} @Override Public voidAftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception ex) {/** * This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true before execution. * This method will be executed after the entire request, that is, dispatcherservlet rendered view execution, the main function of this method is to clean up the resources, * /}}
View Code


2. Configuring interceptors in XML files

After the interceptor is defined, the XML file is declared and the filter rules are added.

<MVC:Interceptors>    <!--written outside, which means to intercept all links--    <Bean ID="" class=""/>    <MVC:Interceptor>     <MVC:Mapping Path="/**" />     <!--exclude blocked links--     <MVC:Exclude-Mapping Path="/static/**" />     <Bean class="Interceptor Java code path" />    </MVC:Interceptor>  </MVC:Interceptors>
View Code


So far, the simple use of SPRINGMVC is that.

3. Springmvc principle

Springmvc interceptors are different from spring interceptors, SPRINGMVC have a unified portal Dispatcherservlet, all requests are through Dispatcherservlet, All operations are done in the order of the servlet, Dispatcherservlet, and there is no proxy for SPRINGMVC managed controllers. It's not hard to imagine that we do certain actions before the controller executes, perform certain actions, and render to do certain actions, all of which are planned by the servlet at the beginning. The SPRINGMVC interceptor corresponds to three prehandle,posthandle,aftercompletion methods.

4. The difference between interceptor and filter

Filter: Dependent on the servlet container. On the implementation of a function callback, almost all requests can be filtered, but the disadvantage is that a filter instance can only be called once when the container is initialized. The purpose of the filter is to do some filtering to get the data we want to get, such as: Modify the character encoding in the filter, modify some parameters of httpservletrequest in the filter, including: Filter vulgar text, dangerous characters, etc.

Interceptors: dependent on the web framework, in SPRINGMVC is dependent on the SPRINGMVC framework. The implementation of the Java-based reflection mechanism belongs to the application of aspect-oriented programming (AOP). Because interceptors are web-based framework calls, you can use spring's dependency injection (DI) for some business operations, while an interceptor instance can be called multiple times within a controller's lifetime. However, the disadvantage is that only the controller requests can be intercepted, and some other requests, such as direct access to static resources, cannot be intercepted.


Attach a servlet execution sequence diagram (excerpt):

5. Differences between STRUTS2 and SPRINGMVC interceptors

Struts2 's custom interceptors have three main methods: Init (), intercept (), Destroy ()

There are also three ways to Springmvc a custom interceptor: prehandle,posthandle,aftercompletion

Struts2 The main differences of three methods:

The Init method, after the Interceptor class is created, is called before the action image is intercepted, which is equivalent to a Post-constructor method, which allows the Interceptor class to do the necessary initial session operations.
The Destroy method is called before the Interceptor is garbage collected, and is used to reclaim resources initialized by the Init method.
Intercept is the main interception method of interceptors, if you need to invoke the subsequent action or interceptor, just call the Invocation.invoke () method in the method, before and after the method call can insert the action call before and after the interceptor needs to do the method. If you do not need to invoke subsequent methods, you can return an object of type string, such as action.success.

Springmvc The main differences of three methods:

A little (as already mentioned above)


In summary, struts2 generally in the Intercept method to perform permissions or other rule validation, the failure to verify the direct return failure result represents the page. While spring is generally checked in Prehandle, the validation fails to forward or redirect directly.

SPRINGMVC Interceptor Use and principle understanding

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.