Use Interceptor in spring MVC

Source: Internet
Author: User
Tags prepare stub

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
  1. Import Javax.servlet.http.HttpServletRequest;
  2. Import Javax.servlet.http.HttpServletResponse;
  3. Import Org.springframework.web.servlet.HandlerInterceptor;
  4. Import Org.springframework.web.servlet.ModelAndView;
  5. public class Springmvcinterceptor implements Handlerinterceptor {
  6. /**
  7. * 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
  8. * 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
  9. * Called before the Controller method call. SPRINGMVC This interceptor chain structure can also be interrupted, this interruption is to make the Prehandle return
  10. * Return value is false, when the return value of Prehandle is false, the entire request ends.
  11. */
  12. @Override
  13. public boolean prehandle (HttpServletRequest request,
  14. HttpServletResponse response, Object handler) throws Exception {
  15. TODO auto-generated Method Stub
  16. return false;
  17. }
  18. /**
  19. * 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
  20. *, 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
  21. 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,
  22. * 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
  23. * 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.
  24. */
  25. @Override
  26. public void Posthandle (HttpServletRequest request,
  27. HttpServletResponse response, Object handler,
  28. Modelandview Modelandview) throws Exception {
  29. TODO auto-generated Method Stub
  30. }
  31. /**
  32. * 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.
  33. * 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.
  34. */
  35. @Override
  36. public void Aftercompletion (HttpServletRequest request,
  37. HttpServletResponse response, Object handler, Exception ex)
  38. Throws Exception {
  39. TODO auto-generated Method Stub
  40. }
  41. }

(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
  1. Import Org.springframework.ui.ModelMap;
  2. Import Org.springframework.web.context.request.WebRequest;
  3. Import Org.springframework.web.context.request.WebRequestInterceptor;
  4. public class Allinterceptor implements Webrequestinterceptor {
  5. /**
  6. * 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
  7. */
  8. @Override
  9. public void Prehandle (WebRequest request) throws Exception {
  10. TODO auto-generated Method Stub
  11. System.out.println ("Allinterceptor ....................)");
  12. 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
  13. 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
  14. 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
  15. }
  16. /**
  17. * This method will be executed before the controller executes, and MODELMAP represents the model object returned after Request controller processing, so you can
  18. * This method modifies the properties of the Modelmap, thus achieving the effect of changing the returned model.
  19. */
  20. @Override
  21. public void Posthandle (WebRequest request, Modelmap map) throws Exception {
  22. TODO auto-generated Method Stub
  23. For (String Key:map.keySet ())
  24. SYSTEM.OUT.PRINTLN (key + "-------------------------");;
  25. Map.put ("Name3", "value3");
  26. Map.put ("Name1", "name1");
  27. }
  28. /**
  29. * 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
  30. */
  31. @Override
  32. public void Aftercompletion (WebRequest request, Exception Exception)
  33. Throws Exception {
  34. TODO auto-generated Method Stub
  35. SYSTEM.OUT.PRINTLN (Exception + "-=-=--=--=-=-=-=-=-=-=-=-==-=--=-=-=-=");
  36. }
  37. }

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
    1. Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
    2. Xsi:schemalocation= "Http://www.springframework.org/schema/mvc
    3. Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "

Here is an example of my declaration:

XML code
  1. <beans xmlns= "Http://www.springframework.org/schema/beans"
  2. Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"
  3. Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
  4. Xsi:schemalocation= "Http://www.springframework.org/schema/beans
  5. Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. Http://www.springframework.org/schema/context
  7. Http://www.springframework.org/schema/context/spring-context-3.0.xsd
  8. Http://www.springframework.org/schema/mvc
  9. 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    
    1. <mvc:interceptors>  
    2.     <!--   Using a bean to define a interceptor, the interceptor directly defined under the Mvc:interceptors root will intercept all requests  -->  
    3.     <bean class= "Com.host.app.web.interceptor.AllInterceptor"/>  
    4.     <mvc:interceptor>  
    5.          <mvc:mapping path= "/test/number.do"/>&NBSP;&NBSP;
    6.          <!--  Defines the  -->   below Mvc:interceptor that is the interception of a particular request;
    7.         <bean class= " Com.host.app.web.interceptor.LoginInterceptor "/>&NBSP;&NBSP;
    8. &NBSP;&NBSP;&NBSP;&NBSP;</MVC: interceptor>  
    9. </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

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.