Using Interceptor interceptors in SPRINGMVC

Source: Internet
Author: User

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 is 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 the aftercompletion  method that we are going to talk about, which is only in the current interceptor   's prehandle  method can be called when the return value is true . 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:

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  The Handlerinterceptor {/** * prehandle method is used for processor interception, as the name implies, the method will be called before the controller is processed. Interceptor interceptors in SPRINGMVC are chained, can exist at the same time  *  multiple interceptor, and then SPRINGMVC will be executed one after the other according to the order of the Declaration, And all Prehandle methods in the interceptor are called before the  * controller method call. This interceptor chain structure of the SPRINGMVC can also be interrupted, which means that the return  *  return value of Prehandle is false, and the entire request ends when the return value of Prehandle is false.  */@Overridepublic  boolean prehandle (httpservletrequest request,httpservletresponse  Response, object handler)  throws Exception {// TODO Auto-generated  Method stubreturn false;} /** *  This method only executes when the current interceptor Prehandle method returns a value of true. The Posthandle is used for processor interception, and its execution time is handled by the processor andnbsp;* , 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 exercise  *  . 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 of the interceptor inside the Struts2, *  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  *  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.  */@Overridepublic  void posthandle (httpservletrequest request,httpservletresponse  Response, object handler,modelandview modelandview)  throws Exception {//  todo auto-generated method stub}/** *  This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true to execute. This method will be used to clean up the resources after the entire request is completed, that is, Dispatcherservlet renders the view execution, *  The main function of this method Of course this method can only be executed if the return value of the current interceptor Prehandle method is true.  */@Overridepublic  void aftercompletion (httpservletrequest request,httpservletresponse  response, object HANDLER, EXCEPTION EX) Throws exception {// todo auto-generated method  stub}}
(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, when we use hibernate , we can prepare a hibernate  session  object in this method, then use the setattribute of webrequest  (name, Value, scope) put it in the properties of the webrequest . Here is the third parameter of the setattribute  method scope  The parameter is an integer type. It defines three constants in the parent-level interface requestattributes  of webrequest :

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,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 after controller  processing, we can change the returned model  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.

    The following 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  The allinterceptor implements webrequestinterceptor {/** *  is executed before the request is processed, and the method is primarily used to prepare the resource data, You can then put them as request attributes into WebRequest  */@Overridepublic  void prehandle (webrequest request)   Throws exception {// todo auto-generated method stubsystem.out.println (" Allinterceptor ... "Request.setattribute (" request ", " request ", ). ..... ..."; ".". ";" "." Webrequest.scope_request);//This is placed within the request scope, so you can only get 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, you can access the Request.setattribute ("Globalsession",  "globalsession" in the normal current session,  webrequest.scope_global_ If the environment allows it to be accessed in a globally shared session, or in a normal current session, the method will return to the}/** *  after the controller executes.Back to the view, Modelmap represents the model object returned after Request controller processing, so you can modify the Modelmap property in the  *  method to achieve the effect of changing the returned model.  */@Overridepublic  void posthandle (webrequest request, modelmap map)  throws  Exception {// TODO Auto-generated method stubfor  (String key: Map.keyset ()) System.out.println (key +  "-------------------------"); Map.put ("Name3",  "Value3"); Map.put ("Name1",  "name1");} /** *  The method is called after the entire request is completed, that is, after the view is rendered, primarily for the release of some resources  */@Overridepublic  void  Aftercompletion (webrequest request, exception exception) throws exception {//  Todo auto-generated method stubsystem.out.println (exception +  "-=-=--=--=-=-=-=-=-=-= -=-==-=--=-=-=-=");}}
second, the definition of the Interceptor class added to the SPRINGMVC interception system

1. Add a schema that supports MVC in the 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 declaration:

<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 ">

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 of mvc:interceptors tags to declare interceptors that need to be added to the SPRINGMVC interceptor chain
<mvc:interceptors><!--use beans to define a interceptor, directly defined under the Mvc:interceptors root interceptor will intercept all requests-->< Bean class= "Com.host.app.web.interceptor.AllInterceptor"/><mvc:interceptor><mvc:mapping path= "/test/ Number.do "/><!--defined below Mvc:interceptor is the--><bean class=" to intercept a specific request " Com.host.app.web.interceptor.LoginInterceptor "/></mvc:interceptor></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.


Using Interceptor interceptors in SPRINGMVC

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.