Implementation of SPRINGMVC Interceptor _1_ Interceptor

Source: Internet
Author: User

SPRINGMVC Interceptor: Blog Articles for the following references

Introduction to Spring MVC

SPRINGMVC Interceptor Implementation principle and login implementation

SPRINGMVC Interceptor detailed [with source analysis]

Learn springmvc--Interceptors

*********************

1-1 Interceptors

Interceptors are enhancements to the function by unifying the interception of requests sent from the browser to the server.

Usage scenarios: Solve common problems with requests (e.g. garbled, permission validation, etc.)

Implementation of ===2 Interceptor ==========================

How---2-1 interceptors work-------------------------------------------

SPRINGMVC can solve garbled problems by configuring filters (filters are very similar to interceptors)

The interceptor works very much like a filter

---2-2 Interceptor implementation-------------------------------------------

1. Write the Interceptor class to implement the Handlerinterceptor interface

Implementation of the following three interfaces

2. Register the Interceptor in the SPRINGMVC frame

Register interceptors in the default configuration file for Springmvc:

1) Added the MVC namespace: xmlns:mvc= "Http://www.springframework.org/schema/mvc"

2) Added SPRINGMVC format descriptor file xsd file

Http://www.springframework.org/schema/mvc
Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p"
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 ">

Add 1) 2) before you can use <mvc:> tags

<mvc:interceptors>

<!--This class is our custom interceptor-->
     <bean id= "Commoninterceptor" class= " Org.shop.interceptor.CommonInterceptor "></bean>
</mvc:interceptors>

3. Configure interception rules for interceptors
<mvc:interceptors>
<mvc:interceptor>
<!--
/** means all folders and subfolders inside the folder.
/* is all folders, without subfolders
/is the root directory of the Web project
<mvc:mapping path= "/**"/>

-
<mvc:mapping path= "/viewall.form"/>
<!--need to exclude the blocked address--
<!--<mvc:exclude-mapping path= "/usercontroller/login"/>--
<bean id= "Commoninterceptor" class= "Org.shop.interceptor.CommonInterceptor" ></bean> <!-- This class is our custom interceptor--
</mvc:interceptor>
<!--when setting up multiple interceptors, call the Prehandle method sequentially, and then call each interceptor's Posthandle and Aftercompletion methods in reverse order--
</mvc:interceptors>

---2-3 Interceptor Method Introduction-------------------------------------------

There are three methods defined in the Handlerinterceptor interface, and we are using these three methods to intercept the user's request.

Prehandle (): This method is called before the business processor processes the request, and the interceptor in SPRINGMVC is a chained call that can exist in one application, or in one request, with multiple interceptor at the same time. Each interceptor call is executed sequentially according to its declaration order, and the first execution is the Prehandle method in Interceptor, so you can do some pre-initialization operations in this method or a preprocessing of the current request. You can also make some judgments in this method to determine whether the request is going to go on. The return value of the method is a Boolean of type bool, and when it returns to false, it means that the request ends and that subsequent interceptor and controllers are no longer executed, and the next interceptor is resumed when the return value is True Prehandle method, which is the Controller method that invokes the current request if it is already the last interceptor.

Parameter: Object handler represents the target object of the chant intercept request

Boolean Prehandle (HttpServletRequest request, httpservletresponse response, Object handler) throws Exception;

-------------------------------------------------------------

Posthandle (): This method executes 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 declared interceptor is executed later.

Parameters:Modelandview modelandview, you can change the actual view by Modelandview parameters, or modify the method that is sent to the view

void Posthandle (HttpServletRequest request, httpservletresponse response, Object handler, Modelandview Modelandview) Throws Exception;

-----------------------------------------------------

aftercompletion (): This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true before it is executed. 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.

Not used.

void Aftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception ex) throws Exception;

Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;ImportOrg.springframework.web.servlet.ModelAndView;ImportOrg.springframework.web.servlet.handler.HandlerInterceptorAdapter; Public classCommoninterceptorextendshandlerinterceptoradapter{Private FinalLogger log = Loggerfactory.getlogger (commoninterceptor.class);  Public  Static  FinalString last_page = "LastPage"; /*** Called before the business processor processes the request * if return false * Aftercompletion () from the current interceptor to execute all interceptors, then exit the Interceptor chain *          * If True * executes the next interceptor until all interceptors are executed * and then executes the intercepted controller * and then enters the interceptor chain, * Execute all Posthandle () from the last interceptor and then back from the last Interceptor All aftercompletion ()*/@Override Public BooleanPrehandle (httpservletrequest request, httpservletresponse response, Object handler)throwsException {if("GET". Equalsignorecase (Request.getmethod ()))            {requestutil.saverequest (); } log.info ("============== Execution Order: 1, prehandle================"); String RequestUri=Request.getrequesturi (); String ContextPath=Request.getcontextpath (); String URL= Requesturi.substring (Contextpath.length ());if("/usercontroller/login". Equals (URL)) {                                      return true; }Else{String username= (String) request.getsession (). getattribute ("User"); if(Username = =NULL) {Log.info ("Interceptor: Jump to login page!" "); Request.getrequestdispatcher ("/page/index.jsp"). Forward (request, response); return false; }Else                            return true; }                    }                /*** After the business processor processes the request execution, the actions performed before the view is generated * can include data in the Modelandview, such as the current time*/@Override Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Modelandview Modelandview)throwsException {log.info ("============== Execution Order: 2, posthandle================"); if(Modelandview! =NULL){//Join Current TimeModelandview.addobject ("haha", "Test Posthandle"); }          }                /*** Called after dispatcherservlet complete processing of the request, can be used to clean up resources, etc. * when an interceptor throws an exception, all interceptors are executed back from the current Interceptor Aftercompletion () */@Override Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object handler, Exception Ex)throwsException {log.info ("============== Execution Order: 3, aftercompletion================"); }  }

---More than 2-4 interceptor applications-------------------------------------------

<mvc:interceptors>

<!--This class is our custom interceptor--
<bean id= "CommonInterceptor1" class= "Org.shop.interceptor.CommonInterceptor1" ></bean>

<bean id= "CommonInterceptor2" class= "Org.shop.interceptor.CommonInterceptor2" ></bean>
</mvc:interceptors>

Execution order:

---2-5 interceptors other implementations-------------------------------------------

Implement the Webrequestinterceptor interface to implement the Interceptor.

Similar to the Handlerinterceptor interface, the difference is that the Webrequestinterceptor Prehandle has no return value. There is also webrequestinterceptor for the request, there is no response in the interface method parameter.

The notation for registering with the SPRINGMVC framework does not change

Cons: The difference is webrequestinterceptor prehandle no return value, cannot terminate the request

  

  

Implementation of SPRINGMVC Interceptor _1_ Interceptor

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.