SpringMVC Learning Record (7) -- Use of interceptor

Source: Internet
Author: User

SpringMVC Learning Record (7) -- Use of interceptor

SpringMVC requests are shown in the following figure:

We can see that all requests are received through Dispatherservlet, and then Handlermapping is used to determine which controller to use, and then ViewResolver is used to determine which view to return. from the process perspective, Handlermapping is the first method we can implement the interceptor. another method is to implement the WebRequestInterceptor interface or inherit its subclass.

1. Implement the HandlerInterceptor Interface

Implement the HandlerInterceptor interface or inherit the sub-classes of HandlerInterceptor. For example, Spring has provided the abstract class HandlerInterceptorAdapter that implements the HandlerInterceptor interface. The following describes how to implement its interface. Let's take a look at the three methods of this interface.
-Method preHandle: As the name suggests, this method will be called before request processing. 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.
-Method postHandle: 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.
-Method afterCompletion: This method is executed only when the returned value of the preHandle method of the corresponding Interceptor 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.

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 suggests, this method will be called before the Controller processes it, the Interceptor in SpringMVC is chained and multiple interceptors can exist at the same time. Then SpringMVC will follow the declared order One execution, and all the preHandle methods in Interceptor will be called before * Controller method call. 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. * // @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// TODO Auto-generated method stub return false ;} /*** 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. * // @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stub}/*** this method is executed only when the current value of the preHandle method of Interceptor 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. * // @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// TODO Auto-generated method stub }}
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.

Method preHandle: The 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: Its value is 0, indicating that it can be accessed only in the request.
SCOPE_SESSION: Its value 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: Its 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.

Method postHandle: 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.

Method afterCompletion: 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.
Import org. springframework. ui. modelMap; import org. springframework. web. context. request. webRequest; import org. springframework. web. context. request. webRequestInterceptor; public class AllInterceptor implements WebRequestInterceptor {/*** is executed before request processing. This method is mainly used to prepare resource data, then you can put them as request attributes in WebRequest */@ Override public void preHandle (WebRequest request) throws Exception {// TODO Auto-generated method stub Syst Em. out. println ("AllInterceptor ............................... "); 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 If allowed, it can be accessed in a globally shared session. Otherwise, it is accessed in a normal current session.}/*** this method will be executed after the Controller is executed and before the view is returned, modelMap indicates the Model object returned after the request is processed by the Controller. Therefore, you can modify the attribute of ModelMap in * to change 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 complete, that is, after the view is rendered, it is mainly used to release some resources */@ Override public void afterCompletion (WebRequest request, Exception exception) throws Exception {// TODO Auto-generated method stub System. out. println (exception + "-= -- =-= ");}}
3. Configure the interceptor 1.mvc: interceptors label to declare 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.

Original link http://haohaoxuexi.iteye.com/blog/1750680

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.