Introduction to Spring Interceptor

Source: Internet
Author: User

Spring Interceptor Brief introduction to common application scenarios

1, log records: Log the request information for information monitoring, information statistics, calculation of PV (Page View) and so on.
2, permission check: such as login detection, enter the processor detection detection is logged in, if not directly back to the login page;
3, performance monitoring: Sometimes the system in a certain period of time inexplicably slow, can pass through the interceptor before entering the processor before the start time, record the end time after processing, so as to get the processing time of the request (if there is a reverse proxy, such as Apache can automatically record);
4, general behavior: Read the cookie to get user information and put the user object into the request, so as to facilitate the subsequent use of the process, as well as the extraction locale, theme information, as long as the multiple processors are required to use the interceptor implementation.
5, Opensessioninview: such as Hibernate, enter the processor to open the session, after the completion of the session closed.

Implementation method

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 spring An abstract class Handlerinterceptoradapter has been provided to implement the Handlerinterceptor interface;
The second approach is to implement the spring Webrequestinterceptor interface, or to inherit the class that implements the Webrequestinterceptor.

First Kind

import javax.servlet.http.HttpServletRequest;    Import Javax.servlet.http.HttpServletResponse;  Import Org.springframework.web.servlet.HandlerInterceptor;    Import Org.springframework.web.servlet.ModelAndView;  Public classSpringmvcinterceptor implements Handlerinterceptor {/** * 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, can exist simultaneously * multiple interceptor, The SPRINGMVC then executes one after the other according to the order of the Declaration, and all Prehandle methods in the interceptor are called before the * Controller method call.      This interceptor chain structure of the SPRINGMVC can also be interrupted, which means that the return value of Prehandle is false, and the entire request ends when the return value of Prehandle is false. */@Override Publicboolean prehandle (httpservletrequest request, httpservletresponse response, Object handler) throws Excep tion {//TODO auto-generated Method Stub        return false; }            /** This method will only be executed if the current interceptor Prehandle method returns a value of true. Posthandle is used for processor interception, its execution time is after the processor to process the *, that is, after the controller's method call execution, but it will be executed before the rendering of the view Dispatcherservlet, That means you can do the Modelandview in this method. The chain structure of this method is the opposite of the normal access direction, that is, the first declaration of the Interceptor Interceptor the 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 called Actioninvocation in Struts2 is called the next interceptor *      Either the action is called and the content to be called before Interceptor is written before invoking invoke, and the content to be called after Interceptor is written after the Invoke method is called. */@Override Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Modela Ndview Modelandview) throws Exception {//TODO auto-generated Method Stub              }        /** * This method is also required for the current corresponding interceptor of the Prehandle method when the return value is true before execution. This method will render the view execution after the entire request is completed, that is, the main function of this method is to clean up the resources, Dispatcherservlet      Of course this method can only be executed if the return value of the current interceptor Prehandle method is true. */@Override Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object handler, Exception ex) Throws Exception {//TODO auto-generated Method Stub              }        }

The second Kind

import Org.springframework.ui.ModelMap;  Import Org.springframework.web.context.request.WebRequest;    Import Org.springframework.web.context.request.WebRequestInterceptor;  Public classAllinterceptor implements Webrequestinterceptor {/** * Executed before request processing, the method is primarily used to prepare the resource data, and can then be placed in the WebRequest as the request attribute*/@Override Public voidPrehandle (WebRequest request) throws Exception {//TODO auto-generated Method StubSystem. out. println ("allinterceptor ......... .... ..........."); Request.setattribute ("Request","Request", webrequest.scope_request);//This is placed within the request scope, so it can only be obtained from the request in the currentRequest.setattribute ("Session","Session", webrequest.scope_session);//This is put in the session scope, if the environment allows it can only be in the local isolated session access, otherwise it is in the normal current session can be accessedRequest.setattribute ("globalsession","globalsession", webrequest.scope_global_session);//it can be accessed in a globally shared session if the environment allows it, otherwise it is accessed in a normal current session    }        /** * This method will be executed before the controller executes, MODELMAP represents the model object returned after Request controller processing, so you can modify the Modelmap property in the * method to achieve a change in the returned model      The effect. */@Override Public voidPosthandle (WebRequest request, Modelmap map) throws Exception {//TODO auto-generated Method Stub         for(String key:map.keySet ()) System. out. println (Key +"-------------------------");; Map.put ("Name3","Value3"); Map.put ("name1","name1"); }        /** This method will be called after the entire request is completed, that is, after the view is rendered, primarily for the release of some resources*/@Override Public voidaftercompletion (WebRequest request, Exception Exception) throws Exception {//TODO auto-generated Method StubSystem. out. println (Exception +"-=-=--=--=-=-=-=-=-=-=-=-==-=--=-=-=-="); }        }
Use the mvc:interceptors tag to declare interceptors that need to be added to the SPRINGMVC interceptor chain
<mvc:interceptors> <!--using beans to define a interceptor, directly defined under the Mvc:interceptors root interceptor will intercept all requests--< Beanclass="Com.xxx.web.interceptor.AllInterceptor"/> <mvc:interceptor> <!--defining requests for interception--<mvc:mapping path="/**"/> <!--define requests that do not need to be intercepted-<mvc:exclude-mapping path="/login/*"/> <!--The expression below Mvc:interceptor is blocked for a specific request--<beanclass="Com.xxx.web.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>

Introduction to Spring Interceptor

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.