The Interceptor interceptor in SpringMVC is also very important and useful. Its main function is to intercept user requests and perform corresponding processing. For example, it can perform permission verification, or determine whether the user is logged in, or determine whether the current time is the ticket purchase time like 12306.
1. Define the Interceptor implementation class
Interceptor intercept requests in SpringMVC are implemented through HandlerInterceptor. Defining an Interceptor in SpringMVC is very simple. There are two main ways. The first way is to define the Interceptor class that implements the Spring HandlerInterceptor interface, or this class inherits the class that implements the HandlerInterceptor interface, such as the abstract class that Spring has provided that implements the HandlerInterceptor interface, which is already provided by Spring; the second way is to implement the Spring WebRequestInterceptor interface, or inherits the class that implements the WebRequestInterceptor interface.
(I) Implementing HandlerInterceptor interface
There are three methods defined in the HandlerInterceptor interface, and we use these three methods to intercept user requests.
(1) preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) method, as the name implies, will be called before the request is processed. Interceptor in SpringMVC is called in a chain form. 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 first ones are executed are the preHandle method in the Interceptor, so some pre-initialization operations can be performed in this method or a pre-processing of the current request, or some judgments can be made in this method to decide whether the request should continue.
The return value of this method is of Boolean type Boolean. When it returns to false, it means that the request ends, and the subsequent Interceptor and Controller will not be executed again; when the return value is true, the preHandle method of the next Interceptor will continue to be called. If it is already the last Interceptor, the Controller method of the current request will be called.
(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 called when the return value of the preHandle method of the current Interceptor to be true.
The postHandle method, as the name suggests, 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 after the Controller process in this method. The direction of the call of the postHandle method is the opposite of preHandle, which means that 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. Then the content in each Interceptor before the invoke method is executed in the declared order, and the content after the invoke method is reversed.
(3) afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) method, this method needs to be executed 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 completed, that is, after the DispatcherServlet renders the corresponding view. The main function of this method is to clean up resources.
Here is a simple code description:
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 { /** * The preHandle method is used for processor interception. As the name suggests, this method will be called before the Controller process. The Interceptor interceptor in SpringMVC is chained, and multiple Interceptors can exist at the same time. Then SpringMVC will execute one by one according to the order of the declaration, and all the preHandle methods in Interceptor will be called before the Controller method is called. SpringMVC's Interceptor chain structure can also be interrupted. This interrupt method makes the return value of preHandle to 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 when the current return value of the preHandle method of the Interceptor is true. postHandle is used for processor interception. Its execution time is after the processor is processed*, that is, after the Controller method is called, but it will be executed before the DispatcherServlet renders the view, which means that in this method you can operate the ModelAndView*. The chain structure of this method is the opposite of the normal access direction, that is, the method declared first will be called later. This is a bit similar to the execution process of the interceptor in Struts2. * Only in the intercept method in Struts2, the invoke method of ActionInvocation should be manually called. The invoke method of ActionInvocation in Struts2 is to call the next Interceptor * or call the action, and then the contents that need to be called before the Interceptor are written before the call to invoke, and the contents that need to be called after the Interceptor are written after the call to the invoke method. */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } /** * This method also needs to be executed when the return value of the current corresponding Interceptor's preHandle method is true. This method will be executed after the entire request is completed, that is, the DispatcherServlet renders the view execution. * The main function of this method is to clean up resources. Of course, this method can only be executed when the current return value of the preHandle method of the Interceptor is true. */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } } (II) Implement the WebRequestInterceptor interface
There are also three methods defined in WebRequestInterceptor, and we also use these three methods to implement interception. All three methods pass the same parameter WebRequest, so what is this WebRequest? This WebRequest is an interface defined by Spring. The method definitions in it are basically the same as HttpServletRequest. All operations performed on WebRequestInterceptor in WebRequestInterceptor will be synchronized to HttpServletRequest, and then passed in the current request.
(1) preHandle(WebRequest request) method. This method will be called before the request is processed, that is, it will be called before the Controller method is called. This method is different from the preHandle in HandlerInterceptor. The main difference is that the return value of the method is void, which means there is no return value. Therefore, we generally use it to prepare resources. For example, when we use Hibernate, we can prepare a Hibernate Session object in this method, and then use the setAttribute(name, value, scope) of WebRequest to put it into the WebRequest property. Here we can talk about the third parameter scope of the setAttribute method, which is of Integer type. Three constants are defined for WebRequest's parent layer interface RequestAttributes:
SCOPE_REQUEST: Its value is 0, which means it is accessible only in request.
SCOPE_SESSION: Its value is 1. If the environment allows it, it represents a local isolated session, otherwise it represents a normal session and can be accessed within the scope of the session.
SCOPE_GLOBAL_SESSION: Its value is 2. If the environment allows it, it represents a globally shared session, otherwise it represents a normal session and can be accessed within the scope of the session.
(2) postHandle(WebRequest request, ModelMap model) method. This method will be called after the request processing, that is, after the Controller method is called, but will be called before the view returns are rendered, so you can change the display of data by changing the data model ModelMap in this method. This method has two parameters. The WebRequest object is used to pass the entire request data. For example, the data prepared in preHandle can be passed and accessed through WebRequest; ModelMap is the Model object returned after the Controller process. We can change the returned Model model by changing its properties.
(3) afterCompletion(WebRequest request, Exception ex) method. This method will be executed after the entire request is processed, that is, after the view is returned and rendered. Therefore, in this method, the resource release operation can be performed. The WebRequest parameter can pass the resources we prepared in preHandle here for release. The Exception parameter represents the currently requested exception object. If the exception thrown in the Controller has been processed by the Spring exception processor, then the exception object is null.
Here is a simple code description:
import org.springframework.ui.ModelMap; import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.request.WebRequestInterceptor; public class AllInterceptor implements WebRequestInterceptor { /** * Execute before the request is processed. This method is mainly used to prepare resource data, and then they can be put into WebRequest as request attributes*/ @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 scope of the request, so you can only get request.setAttribute("session", "session", in the request in the current request. WebRequest.SCOPE_SESSION);//This is placed within the session scope. If the environment allows it, it can only be accessed in a locally isolated session. Otherwise, it can be accessed in the 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 can be accessed in the normal current session} /** * This method will be executed after the Controller is executed and before returning to the view. ModelMap represents the Model object returned after the Controller is requested to process the Controller, so the properties of the ModelMap can be modified in this method to achieve 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 + "--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- afterCompletion(WebRequest request, Exception exception) throws Exception { // TODO Auto-generated method stub System.out.println(exception + "-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); } }2. Add the defined interceptor class to the intercept system of SpringMVC
1. Add a schema that supports MVC in 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 statement:
<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">
In this way, you can use the mvc tag in the SpringMVC configuration file. There is a mvc:interceptors in the mvc tag that is used to declare the interceptor of SpringMVC.
(II) Use the mvc:interceptors tag to declare the interceptor that needs to be added to the SpringMVC interceptor chain
<mvc:interceptors> <!-- Use bean to define an Interceptor. The Interceptor directly defined under the root of mvc:interceptors will intercept all requests --> <bean/> <mvc:interceptor> <mvc:mapping path="/test/number.do"/> <!-- The representation defined under mvc:interceptor is to intercept a specific request --> <bean/> </mvc:interceptor> </mvc:interceptor>
From the above example, we can see that a series of interceptors can be declared using the mvc:interceptors tag, and then they can form an interceptor chain. The execution order of the interceptor is executed in the order of declarations. The preHandle method in the declared interceptor will be executed first, but its postHandle method and afterCompletion method will be executed later.
There are two main ways to declare interceptor under the mvc:interceptors tag:
(1) Directly define a bean object of the Interceptor implementation class. Interceptor interceptor declared in this way will intercept all requests.
(2) Use the mvc:interceptor tag to declare. Interceptor declared in this way can define the request path that needs to be intercepted through the mvc:mapping subtag.
After the above two steps, the defined interceptor will act to intercept specific requests.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.