spring Learning (thirty-three) - interceptor

Interceptor SpringMVC the interceptor is also very important and very useful, and its primary role is to intercept the user's request and performs corresponding processing. For example, use it to verify permissions, or whether a user is logged in, or is it looks like 12306 to determine whether the current time is the time of purchase.

  A, defines the implementation class Interceptor

 Interceptor SpringMVC interception request is achieved by HandlerInterceptor. In SpringMVC Interceptor define a very simple, there are two ways, first way is to define the class Interceptor to achieve the Spring of HandlerInterceptor interface, or is this class inherits HandlerInterceptor class that implements the interface, such as already provided Spring implements the abstract class HandlerInterceptorAdapter HandlerInterceptor interface; second way is to achieve the Spring WebRequestInterceptor interface, or inherited achieved WebRequestInterceptor class.

(A) implement the interface HandlerInterceptor

HandlerInterceptor interface defines three methods, we are treated to intercept the user's request through these three methods.

   (1) preHandle (HttpServletRequest request, HttpServletResponse response, Object handle) method, as the name implies, this method will be called before the request processing. SpringMVC Interceptor is a chain of calls, or may be present in a plurality of request Interceptor simultaneously in one application. Each call to the Interceptor sequentially performed in terms of its declaration order, the first and preHandle Interceptor methods are executed, it is possible to make some pre-initialization in this method is a pretreatment, or the current request, and you can make some judgment in this method to determine whether the request should continue. The return value of this process is Boolean Boolean type, when it returns to false, indicating the end of the request, and the subsequent Interceptor Controller will no longer performed; when the return value is true preHandle will continue to call a method in the Interceptor If a Interceptor is the last time will be calling Controller method the current request.

   (2) postHandle (HttpServletRequest request, HttpServletResponse response, Object handle, ModelAndView modelAndView) method, a method of interpretation preHandle we know this method include the back to say to afterCompletion method can only be returned in preHandle method of Interceptor currently belongs in order to be called when the value is true. postHandle method, by definition is after the current request is processed, which is executed after Controller method call, but it would be to be called before the view returns rendered DispatcherServlet, so we can operate on ModelAndView object after Controller process in this method. Direction with preHandle postHandle method is called is reversed, postHandle Interceptor method of execution that is contrary to the statement after the meeting, which Interceptor and implementation of Struts2 inside a little type. Execution of Struts2 inside the Interceptor is a chain, but the inside needs to call Struts2 manually invoke methods ActionInvocation to trigger the next Interceptor or Action calls, then the contents of each Interceptor before invoke method calls are in accordance with declaration order execution, and after the contents invoke method is reversed.

   (3) afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handle, Exception ex), the method also requires a current corresponding to the Interceptor preHandle method are performed when the return value is true. As the name implies, the method after the entire request, that is a corresponding view DispatcherServlet rendered after execution. The main role of this method is that the resources for clean-up work.

Here is described a simple code:

interceptors Package; 

Import the javax.servlet.http.HttpServletRequest; 
Import javax.servlet.http.HttpServletResponse; 
Import org.springframework.stereotype.Component; 
Import org.springframework.web.servlet.ModelAndView; 
Import the org.springframework.web.servlet. handler.HandlerInterceptorAdapter; 

@Component 
public  class LoginInterceptor the extends the cunningly named HandlerInterceptorAdapter { 

    / * * 
     * the preHandle a processor is used to intercept, as the name implies, this method will be called before controller processing 
     * SpringMVC the interceptor interceptor is a chain to be exist 
     * plurality Interceptor, then one after SpringMVC contextually statement execution order, and all of the Interceptor methods will in preHandle 
     be called before * Controller method call. This SpringMVC Interceptor chain structure may also be interrupted, this interrupt is to make a return preHandle
     * Return value is false, when preHandle of returns false when the entire request is over. 
     * /   
    @Override 
    public Boolean The preHandle (the HttpServletRequest Request, Response the HttpServletResponse, Object Handler) 
        throws Exception { 
        the System. OUT .println ( " the parameterMap = " + request.getParameterMap ()); 
        . The System OUT .println ( " inputStream = " + Request .getInputStream ());
         return  true ; 
    } 
    
    / * * 
     * this method returns true only in the current preHandle this method will be performed when the Interceptor. postHandle intercept processor is used, the execution time is processed in a processor of 
     * after, that is, after the Controller's execution method call, but it will be executed before rendering views in DispatcherServlet, which means you can ModelAndView be operated in this method 
     * for. This method of chain structure is normally accessed with the opposite direction, Interceptor interceptor method that is the first statement after the meeting but called it inside with Struts2 interceptor implementation process a bit like,
     * Just intercept method Struts2 inside you want to invoke a method to manually call ActionInvocation of, Struts2 the invoke method calls ActionInvocation is call the next Interceptor 
     * or call the action, then the contents to be called before the Interceptor are written before the call to invoke, content to be called after the Interceptor are written after the call to invoke methods. 
     * /   
    @Override 
    public  void The postHandle ( 
            the HttpServletRequest Request, Response the HttpServletResponse, Object Handler, ModelAndView ModelAndView) 
            throws Exception { 
    } 
    
    / * *  
     are performed when the process is to return * this method requires preHandle corresponding to the Interceptor is true. The method is completed after the entire request, i.e. DispatcherServlet view to rendering,
     * The main role of this method is used to clean up the resources, of course, this method can only this current Interceptor will be executed when the return value of true preHandle methods. 
     * /   
    @Override 
    public  void afterCompletion ( 
            the HttpServletRequest Request, Response the HttpServletResponse, Object Handler, Exception EX) 
            throws Exception { 
    } 
    
}
    

 

(B) implement the interface WebRequestInterceptor

 WebRequestInterceptor also defines three methods, we are to achieve the interception through these three methods. These three methods are passed the same parameter WebRequest, then what is this WebRequest it? This is WebRequest Spring define an interface, which defines a method which are basically the same with HttpServletRequest, all operations of the WebRequest WebRequestInterceptor will be synchronized to the HttpServletRequest, and has been passed in the current request.

   (1) preHandle (WebRequest request) method. This method will be called before the request is processed, that will be called before Controller method call. This method with HandlerInterceptor in preHandle are different, the main difference lies in the method's return value is void, that is no return value, so we generally mainly use it to carry out preparatory work resources, such as we can when using Hibernate Hibernate this method to prepare a Session object, and then use the WebRequest setAttribute (name, value, scope) WebRequest put it in the properties. Here the third parameter can talk setAttribute scope of this method, which is a parameter of type Integer. The parent layer in the interface RequestAttributes WebRequest it defines three constants:

   SCOPE_REQUEST: its value is 0, representing the only access to the request in.

   SCOPE_SESSION: its value is 1, if the environment allows it to isolate it represents a local session, or the session on behalf of the ordinary, and may be accessed within the session scope.

   SCOPE_GLOBAL_SESSION: its value is 2, if the environment allows it, it represents a globally shared session, or on behalf of the ordinary session, and can be accessed within the scope of the session.

   (2) postHandle (WebRequest request, ModelMap model) method. This method will be processed after the request, which is to be called after Controller method call, but will be called in the returned view is rendered before, so you can change the data model ModelMap in which this method to change the display of the data. This method has two parameters, the WebRequest objects are used to transfer the entire requested data, such data are prepared in the preHandle and access may be delivered by WebRequest; ModelMap is Model Controller object returned after processing, we can change the model attributes to change the model returned.

   (3) afterCompletion (WebRequest request, Exception ex) method. The method may request the entire process is completed, return is executed in view and after rendering. Therefore, in the method of operating the resource can be released. The WebRequest parameter passed to the resources we can prepare in preHandle in here to be released. Exception is the exception object parameter indicates the current request, if thrown in the Controller of Spring has been an exception to the exception handler handled the case, then this is the exception object is null.

Here is described a simple code:

interceptors Package; 

Import org.springframework.stereotype.Component; 
Import org.springframework.ui.ModelMap; 
Import org.springframework.web.context.request.WebRequest; 
Import org.springframework.web.context.request.WebRequestInterceptor; 

@Component 
public  class SessionInterceptor the implements WebRequestInterceptor { 

    / * * 
     * processing performed prior to the request, the method is mainly used to prepare the resource data, and then they can be placed in WebRequest as requested attribute 
     * /   
    @Override 
    public  void the preHandle (WebRequest request) 
        throws Exception { 
        // this request is placed within range, you can request the current request acquired in   
        request.setAttribute ( " request ", " Request " , WebRequest.SCOPE_REQUEST);
         // this is the place, if circumstances permit, then it can only be accessed in partial isolation of the session within the scope of the session, otherwise, it is in general the current session can be accessed   
        request.setAttribute ( " the session " , " the session " , WebRequest.SCOPE_SESSION);
         // if the environment permits, it can access the global shared session, otherwise, it is accessed in a normal current session   
        request.setAttribute ( " globalSession " , " globalSession " , WebRequest.SCOPE_GLOBAL_SESSION); 
        . the System OUT .println ( " sessionId = " + Request.getSessionId());
    }
    
    
    /** 
     * This method will be performed after Controller, before execution returns view, representing a request ModelMap Model Controller object returned after processing, it is possible 
     to modify the properties of ModelMap * this method, so as to achieve the effect of changing the model returns. 
     * /   
    @Override 
    public  void The postHandle (the WebRequest Request, a ModelMap Model) 
            throws Exception { 
        
    } 

    / * * 
     * This method, that is to say after the call view rendering is completed after the entire request, mainly used to free up some resources 
     * / 
    @Override 
    public  void afterCompletion (the WebRequest Request, Exception EX) 
            throws Exception { 
    } 
    
}

 

Second, the definition of the class is added to the interceptor to intercept system SpringMVC

  

<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 ">
      
     ! <- pack scan interceptor is located, to instantiate the interceptor -> 
     <context: scan-Component Base -package = " interceptors " /> 
     
     <- configuration interceptor ->! 
     <MVC: interceptors >   
         <! - definition of a bean using the interceptor, directly defined in mvc: interceptors below the root interceptor will intercept all requests ->   
         <bean class = " interceptors.SessionInterceptor " />   
          
         <MVC: interceptor>  
             <MVC:mapping path=" / littleController / getLittleBallName " />   
             <- defined in mvc:! interceptor following expression is mvc: mapping configuration request to intercept only -> 
       <the bean class = " interceptors.LoginInterceptor " / >
     </ MVC: Interceptor>
   </ MVC: interceptors>
</ Beans>

As can be seen from the above example may be utilized mvc: interceptors series of label claim interceptors, then they can form a chain interceptor, the execution order of interceptors are executed in the order stated, the first statement Interceptor the preHandle method will first execute, but its methods and postHandle afterCompletion method but it will after execution.

          In mvc: interceptors under the label statement interceptor There are two main ways:

                    (1) defines the direct object Interceptor bean implementation class. This way declared Interceptor interceptor will intercept all requests.

                    (2) use mvc: interceptor label statement. Using this method can be declared Interceptor mvc: request to define the required path intercept mapping sub-tab.

          After the above two steps, the definition of the role of interceptor intercepts a specific request occurs.

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/gllegolas/p/11862800.html