The Interceptor interceptor in SPRINGMVC is also very important and useful, and its main function is to intercept the user's request and handle it accordingly. For example, through it to verify the permissions, or to determine whether the user is logged on, or if the current time is like 12306 to determine whether the purchase time.
First, define the interceptor implementation class
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.
(i) Implementation of the Handlerinterceptor interface
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, as the name implies, the method will be 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 . Therefore, you can do some pre-initialization operations in this method or a preprocessing of the current request, or you can make some judgments in this method to determine whether the request should continue. The return value of the method is a Boolean of type bool, and when it returns to false , the request ends, and subsequent interceptor and controller are no longer executed; When the return value is true will continue to invoke the next interceptor 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, explained by the prehandle method we know that this method includes what is to be said later aftercompletion The interceptor method can only be called if the return value of the prehandle method of the currently-owned true is the same. 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 is returned 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 first declaration is executed after the interceptor , and Struts2 The execution of the interceptor inside the is somewhat of a type. struts2 inside the interceptor execution process is also chained, but in struts2 need to manually call actioninvocation invoke method to trigger a call to the next interceptor or action , and then the contents of each interceptor before the invoke method call are executed in the order declared, and the Invoke The content behind the 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.
Here is a simple code description:
Java code
- Import Javax.servlet.http.HttpServletRequest;
- Import Javax.servlet.http.HttpServletResponse;
- Import Org.springframework.web.servlet.HandlerInterceptor;
- Import Org.springframework.web.servlet.ModelAndView;
- public class Springmvcinterceptor 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, 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 interruption is to make the Prehandle return
- * Return value is false, when the return value of Prehandle is false, the entire request ends.
- */
- @Override
- public boolean prehandle (HttpServletRequest request,
- HttpServletResponse response, Object handler) throws Exception {
- 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 in the processor processing
- *, which is executed after the controller's method call, but it executes before the Dispatcherservlet renders the view, that is, in this method you can perform a Modelandview
- For 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, Struts2 calls the Actioninvocation's Invoke method is called the next interceptor
- * Either call the action and then 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 void Posthandle (HttpServletRequest request,
- HttpServletResponse response, Object handler,
- Modelandview Modelandview) throws Exception {
- TODO auto-generated Method Stub
- }
- /**
- * This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true before execution. The method will render the view execution after the entire request is completed, that is, Dispatcherservlet.
- * The main function of this method is to clean up resources, of course, this method can only be executed when the return value of the current interceptor Prehandle method is true.
- */
- @Override
- public void Aftercompletion (HttpServletRequest request,
- HttpServletResponse response, Object handler, Exception ex)
- Throws Exception {
- TODO auto-generated Method Stub
- }
- }
(ii) Realization of the Webrequestinterceptor interface
Three methods are also defined in Webrequestinterceptor, and we are using these three methods to achieve interception. These three methods all pass the same parameter WebRequest, so what is this WebRequest? This WebRequest is an interface defined by spring, and its method definitions are basically the same as HttpServletRequest, in Webrequestinterceptor WebRequest All actions are synchronized to httpservletrequest and then passed in the current request.
(1) Prehandle (WebRequest request) method. The method will be called before the request is processed, meaning it will be called before the Controller method call. This method is different from the Prehandle in Handlerinterceptor, the main difference is that the return value of the method is void, that is, there is no return value, so we generally use it to prepare resources, for example, we are using hibernate You can prepare a Hibernate session object in this method, and then use WebRequest's setattribute (name, value, scope) to place it in the WebRequest attribute. Here's the third parameter to the SetAttribute method, scope, which is an integer type. In WebRequest's parent interface Requestattributes, it defines three constants:
Scope_request: Its value is 0, which means that it can be accessed only in REQUEST.
Scope_session: Its value is 1, if the environment allows it to represent a partial isolated session, otherwise it represents a normal session, and can be accessed within the session range.
Scope_global_session: Its value is 2, if the environment allows, it represents a global shared session, otherwise it represents the normal session, and within the scope of the session can be accessed.
(2) Posthandle (WebRequest request, Modelmap model) method. This method will be called after the request is processed, that is, after the controller method call, but will be called before the view returns are rendered, so you can change the presentation of the data by changing the data model Modelmap in this method. The method has two parameters, the WebRequest object is used to pass the entire request data, such as the data prepared in Prehandle can be passed through WebRequest and access; Modelmap is the model object returned by the controller after processing, We can change the returned model by changing its properties.
(3) Aftercompletion (WebRequest request, Exception Ex) method. The method is executed after the entire request process is completed, that is, after the view is returned and rendered. Therefore, the method can be used to release the resources of the operation. The WebRequest parameter can then pass the resources we have prepared in Prehandle to be released here. The Exception parameter represents the currently requested exception object, which is null if the exception thrown in the controller has already been handled by spring's exception handler.
Here is a simple code description:
Java code
- Import Org.springframework.ui.ModelMap;
- Import Org.springframework.web.context.request.WebRequest;
- Import Org.springframework.web.context.request.WebRequestInterceptor;
- public class Allinterceptor 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 a request attribute
- */
- @Override
- public void Prehandle (WebRequest request) throws Exception {
- TODO auto-generated Method Stub
- System.out.println ("Allinterceptor ....................)");
- Request.setattribute ("Request", "request", webrequest.scope_request);//This is placed within the request scope, so it can only be obtained in the request in the current
- Request.setattribute ("Session", "session", webrequest.scope_session);//This is placed in the session scope, if the environment allows it can only be accessed in a partial isolated session, Otherwise, it can be accessed in a normal current session
- Request.setattribute ("Globalsession", "globalsession", webrequest.scope_global_session);//If the environment allows it, it can be accessed in a globally shared session , otherwise it is accessed in a normal current session
- }
- /**
- * This method will be executed before the controller executes, and MODELMAP represents the model object returned after Request controller processing, so you can
- * This method modifies the properties of the Modelmap, thus achieving the effect of changing the returned model.
- */
- @Override
- public void Posthandle (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 void Aftercompletion (WebRequest request, Exception Exception)
- Throws Exception {
- TODO auto-generated Method Stub
- SYSTEM.OUT.PRINTLN (Exception + "-=-=--=--=-=-=-=-=-=-=-=-==-=--=-=-=-=");
- }
- }
Second, the definition of the Interceptor class added to the SPRINGMVC interception system
1. Add the Schemaxml code that supports MVC in the SPRINGMVC configuration file
- Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
- Xsi:schemalocation= "Http://www.springframework.org/schema/mvc
- Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "
Here is an example of my declaration:
XML code
- <beans xmlns= "Http://www.springframework.org/schema/beans"
- Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"
- Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
- Xsi:schemalocation= "Http://www.springframework.org/schema/beans
- Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- Http://www.springframework.org/schema/context
- Http://www.springframework.org/schema/context/spring-context-3.0.xsd
- Http://www.springframework.org/schema/mvc
- Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">
This allows the MVC tag to be used in the SPRINGMVC configuration file, with an mvc:interceptors in the MVC tag that declares the SPRINGMVC interceptor.
(ii) Use the mvc:interceptors tag to declare the interceptor XML code that needs to be added to the SPRINGMVC interceptor chain
- <mvc:interceptors>
- <!-- Using a bean to define a interceptor, the interceptor directly defined under the Mvc:interceptors root will intercept all requests -->
- <bean class= "Com.host.app.web.interceptor.AllInterceptor"/>
- <mvc:interceptor>
- <mvc:mapping path= "/test/number.do"/>&NBSP;&NBSP;
- <!-- Defines the --> below Mvc:interceptor that is the interception of a particular request;
- <bean class= " Com.host.app.web.interceptor.LoginInterceptor "/>&NBSP;&NBSP;
- &NBSP;&NBSP;&NBSP;&NBSP;</MVC: interceptor>
- </mvc:interceptors>
The above example shows that the mvc:interceptors tag can be used to declare a series of interceptors, and then they can form an interceptor chain, and the order of execution of the interceptor is executed in the order of the Declaration, and the Prehandle method in the first declared interceptor executes first. However, its posthandle methods and Aftercompletion methods are then executed.
There are two main ways of declaring interceptor under the Mvc:interceptors tab:
(1) A Bean object that directly defines a interceptor implementation class. Interceptor interceptors declared in this manner will intercept all requests.
(2) Use the Mvc:interceptor label for Declaration. Interceptor that are declared in this way can define the request path that needs to be intercepted through the mvc:mapping child tag.
After the above two steps, the defined interceptor will take effect to intercept the specific request.
Reprinted from http://elim.iteye.com/blog/1750680
Use interceptor in spring MVC