Use of interceptor in SpringMVC

Source: Internet
Author: User

Use of interceptor in SpringMVC

The Interceptor in SpringMVC is also very important and useful. Its main function is to intercept user requests and process them accordingly.

For example, you can use it to perform permission verification, or to determine whether the user logs in, or to determine whether the current time is the time when the user buys the ticket, as shown in Figure 12306.

1. Define the Interceptor implementation class

Interceptor in SpringMVC intercepts requests through HandlerInterceptor. It is very simple to define an Interceptor in SpringMVC. There are two main methods. The first method is to define the Interceptor class to implement the Spring HandlerInterceptor interface, or this class inherits the class that implements the HandlerInterceptor interface. For example, Spring has provided the abstract class HandlerInterceptorAdapter that implements the HandlerInterceptor interface. The second method is to implement the Spring WebRequestInterceptor interface, or inherit the class that implements WebRequestInterceptor.

(1) Implement the HandlerInterceptor Interface

The HandlerInterceptor interface defines three methods. We use these three methods to intercept user requests.

(1) The preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) method, as the name suggests, will be called before the request is processed. Interceptor in SpringMVC is a chained call. Multiple interceptors can exist in an application or in a request at the same time. The call of each Interceptor is executed in sequence based on the declared order, and the first method to be executed is the preHandle method in Interceptor, therefore, you can perform some pre-initialization operations in this method or a pre-processing of the current request. You can also make some judgments in this method to determine whether the request will continue. The return value of this method is Boolean. If the return value is false, the request is terminated, and the Interceptor and Controller will not be executed; when the return value is true, the preHandle method of the next Interceptor will 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 includes the afterCompletion method to be mentioned later. It can only be called when the returned value of the preHandle method of the current Interceptor is true. The postHandle method, as its name implies, is executed after the current request is processed, that is, after the Controller method is called, but it will be called before DispatcherServlet performs view return rendering, therefore, we can operate the ModelAndView object processed by the Controller in this method. The postHandle method is called in the opposite direction than the preHandle method. That is to say, the declared Interceptor's postHandle method is executed after the meeting, which is somewhat different from the Interceptor Execution Process in Struts2. The execution process of Interceptor in Struts2 is also chained, but in Struts2, you must manually call the ActionInvocation invoke method to trigger the next Interceptor or Action call, then, the content of each Interceptor before the invoke method call is executed in the declared order, and the content after the invoke method is reversed.

(3) The afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex) method is executed only when the returned value of the current corresponding Interceptor preHandle method is true. As the name suggests, this method will be executed after the entire request is completed, that is, after DispatcherServlet renders the corresponding view. This method is mainly used to clean up resources.

The following is a simple code description:

Java code
  1. Importjavax. servlet. http. httpServletRequest; importjavax. servlet. http. httpServletResponse; importorg. springframework. web. servlet. handlerInterceptor; importorg. springframework. web. servlet. modelAndView; publicclassSpringMVCInterceptorimplementsHandlerInterceptor {/*** preHandle method is used for processor interception. As the name suggests, this method will be called before Controller processing. The Interceptor in SpringMVC is chained, multiple interceptors can exist at the same time, and SpringMVC will execute them one by one according to the declared order, and all the Int The preHandle method in erceptor is called before * Controller method is called. SpringMVC's Interceptor chain structure can also be interrupted. In this way, the returned value of preHandle * is false. When the returned value of preHandle is false, the entire request will end. * // @ OverridepublicbooleanpreHandle (HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler) throwsException {// TODOAuto-generatedmethodstubreturnfalse ;} /*** this method will be executed only when the current Interceptor's preHandle method returns true. PostHandle is used for processor interception. Its execution time is after the processor processes *, that is, after the Controller method is called, however, it will be executed before DispatcherServlet renders the view. That is to say, in this method, you can operate on ModelAndView. The chain structure of this method is opposite to that of normal access. That is to say, the first declared Interceptor is called after the method, which is a bit like the execution process of the Interceptor in Struts2, * Only the intercept method in Struts2 needs to manually call the ActionInvocation invoke method. In Struts2, The invoke method that calls ActionInvocation is to call the next Interceptor * or call action, the content to be called before Interceptor is written before invoke is called. The content to be called after Interceptor is written after invoke method is called. * // @ OverridepublicvoidpostHandle (HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler, ModelAndViewmodelAndView) throwsException {// TODOAuto-generatedmethodstub}/*** this method is executed only when the returned value of the current corresponding Interceptor preHandle method is true. This 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 returned value of the current Interceptor preHandle method is true. * // @ OverridepublicvoidafterCompletion (HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler, Exceptionex) throwsException {// TODOAuto-generatedmethodstub }}
(2) Implement the WebRequestInterceptor Interface

WebRequestInterceptor also defines three methods. We also use these three methods to intercept them. All three methods pass the same WebRequest parameter. What is this WebRequest? This WebRequest is an interface defined by Spring, and its method definition is basically the same as HttpServletRequest. All operations performed on WebRequest in WebRequestInterceptor will be synchronized to HttpServletRequest, then it is 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 this method is void, that is, there is no return value. Therefore, we generally use this method to prepare resources, for example, when using Hibernate, we can prepare a Hibernate Session object in this method, and then put it into the attributes of WebRequest using setAttribute (name, value, scope) of WebRequest. Here we can talk about the third parameter scope of the setAttribute method. This parameter is of the Integer type. In the WebRequest's parent interface RequestAttributes, it defines three constants:

SCOPE_REQUEST: The value is 0, indicating that the request can only be accessed.

SCOPE_SESSION: the value of SCOPE_SESSION is 1. If the environment permits it, it indicates a local isolated session. Otherwise, it indicates a normal session and can be accessed within the session range.

SCOPE_GLOBAL_SESSION: The value is 2. If the environment permits it, it indicates a global shared session. Otherwise, it indicates a normal session and can be accessed within the session range.

(2) postHandle (WebRequest request, ModelMap model) method. This method will be called after the request is processed, that is, after the Controller method is called, but will be called before the view return is rendered, therefore, you can change the data presentation by changing the data model ModelMap in this method. This method has two parameters. The WebRequest object is used to transmit the entire request data. For example, the data prepared in preHandle can be transmitted and accessed through WebRequest; modelMap is the Model object returned by the Controller after processing. We can change the returned Model by changing its attributes.

(3) afterCompletion (WebRequest request, Exception ex) method. This method is executed after the entire request is processed, that is, after the view is returned and rendered. Therefore, you can release resources in this method. The WebRequest parameter can transfer the resources we have prepared in preHandle to this place for release. The Exception parameter indicates the Exception object of the current request. If the Exception thrown in Controller has been processed by Spring's Exception processor, the Exception object is null.

The following is a simple code description:

Java code
  1. Importorg. springframework. ui. modelMap; importorg. springframework. web. context. request. webRequest; importorg. springframework. web. context. request. webRequestInterceptor; publicclassAllInterceptorimplementsWebRequestInterceptor {/*** is executed before request processing. This method is mainly used to prepare resource data, then they can be put as request attributes in WebRequest */@ OverridepublicvoidpreHandle (WebRequestrequest) throwsException {// TODOAuto-generatedmethodstubSystem.out.println ("AllInterce Ptor ............................... "); request. setAttribute ("request", "request", WebRequest. SCOPE_REQUEST); // This is within the request range, so the request can only be obtained in the current request. setAttribute ("session", "session", WebRequest. SCOPE_SESSION); // This is put within the session range. If the environment permits it, it can only be accessed in a locally isolated session; otherwise, it can be accessed in a normal current session. setAttribute ("globalSession", "globalSession", WebRequest. SCOPE_GLOBAL_SESSION); // if the environment permits, it can be accessed in a globally shared session; otherwise, it will be accessed in a normal current session} /*** This method will be executed after the Controller executes and before the view is returned. ModelMap indicates the Model object returned after the Controller is processed. Therefore, you can modify the attributes of ModelMap in, to change the returned model. * // @ OverridepublicvoidpostHandle (WebRequestrequest, ModelMapmap) throwsException {// TODOAuto-generatedmethodstubfor (Stringkey: map. keySet () System. out. println (key + "-----------------------"); map. put ("name3", "value3"); map. put ("name1", "name1");}/*** this method will be called after the entire request is complete, that is, after the view is rendered, it is mainly used to release some resources */@ OverridepublicvoidafterCompletion (WebRequestrequest, Exceptionexception) throwsException {// TODOAuto-generatedmethodstubSystem.out.println (exception + "-= -- = -= ");}}
2. Add the defined interceptor class to SpringMVC's interception system. 1. Add the schemaXml code supporting MVC in the SpringMVC configuration file.
  1. Xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemaLocation = "http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"

The following is my declaration example:

Xml Code

    In this way, the mvc tag can be used in the SpringMVC configuration file. The mvc tag contains mvc: interceptors, which is used to declare SpringMVC interceptor.

    (2) Use the mvc: interceptors tag to declare the Xml code of the Interceptor to be added to the SpringMVC interceptor chain

    From the above example, we can see that the mvc: interceptors tag can be used to declare a series of interceptors, and then they can form an interceptor chain. The execution sequence of the interceptor is executed in the order of declaration, the preHandle method in the interceptor declared first is executed, but its postHandle method and afterCompletion method are executed afterwards.

    The following two methods can be used to declare interceptor under the mvc: interceptors label:

    (1) define a bean object of the Interceptor implementation class. The Interceptor declared in this way intercepts all requests.

    (2) Use the mvc: interceptor label for declaration. The Interceptor declared in this way can use the mvc: mapping sub-tag to define the Request Path to be intercepted.

    After the preceding two steps, the defined interceptor intercepts specific requests.

    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.