Spring MVC Interceptor

Source: Internet
Author: User

First, define your own interceptor.

The class that needs our definition inherits Handlerinterceptor into a custom interceptor

 PackageCn.interceptor;ImportOrg.springframework.web.servlet.HandlerInterceptor;ImportOrg.springframework.web.servlet.ModelAndView;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Created by Jingpeppe on 2017/1/12.*/ Public classFirstinterceptorImplementsHandlerinterceptor {@Override Public BooleanPrehandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o)throwsException {System.out.println ("==============myinterceptor.prehandle ()"); return true; } @Override Public voidPosthandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, ModelAndView Modelandview)throwsException {System.out.println ("===============myinterceptor.posthandle ()"); } @Override Public voidAftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Exception E )throwsException {System.out.println ("================myinterceptor.aftercompletion ()"); }}

Second, in the Applicationcontext.xml configuration

mvc:interceptors><Mvc:interceptor>        <mvc:mappingPath="/**" />        <Beanclass= "Cn.interceptor.FirstInterceptor"></Bean>   </Mvc:interceptor></mvc:interceptors>

Firstcontroller.java

 Package Cn.interceptor; Import Org.springframework.stereotype.Controller; Import org.springframework.web.bind.annotation.RequestMapping; /**  */@Controllerpublicclass  Firstcontroller {    @ Requestmapping ("/first.do")    public  String dofirst () {          return "/index.jsp";    }}

Xml

<?XML version= "1.0" encoding= "UTF-8"?><Web-appxmlns= "Http://xmlns.jcp.org/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version= "3.1">    <!--Core Controller -    <servlet>        <Servlet-name>Sprigmvc</Servlet-name>        <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>        <Init-param>            <Param-name>Contextconfiglocation</Param-name>            <Param-value>Classpath:applicationContext.xml</Param-value>        </Init-param>        <Load-on-startup>1</Load-on-startup>    </servlet>    <servlet-mapping>        <Servlet-name>Sprigmvc</Servlet-name>        <Url-pattern>*.do</Url-pattern>    </servlet-mapping></Web-app>

Flow chart

Multiple interceptor configurations define multiple interceptor classes

Add one more connector class on the basis of a single interceptor Secondinterceptor.java

 PackageCn.interceptor;ImportOrg.springframework.web.servlet.HandlerInterceptor;ImportOrg.springframework.web.servlet.ModelAndView;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Created by Jingpeppe on 2017/1/12.*/ Public classSecondinterceptorImplementsHandlerinterceptor {@Override Public BooleanPrehandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o)throwsException {System.out.println ("===second===========myinterceptor.prehandle ()"); return true; } @Override Public voidPosthandle (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, ModelAndView Modelandview)throwsException {System.out.println ("===second============myinterceptor.posthandle ()"); } @Override Public voidAftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse, Object o, Exception E )throwsException {System.out.println ("===second=============myinterceptor.aftercompletion ()"); }}

Applicationcontext.xml

<!--Configuring Interceptors -<mvc:interceptors>    <Mvc:interceptor>        <mvc:mappingPath="/**" />        <Beanclass= "Cn.interceptor.FirstInterceptor"></Bean></Mvc:interceptor>    <Mvc:interceptor>        <mvc:mappingPath="/**" />        <Beanclass= "Cn.interceptor.SecondInterceptor"></Bean>    </Mvc:interceptor></mvc:interceptors>

Flow chart

implementing 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 The response, Object handle) method, as the name implies, 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, 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.

(2) Posthandle (HttpServletRequest request, HttpServletResponse Response, Object handle, Modelandview Modelandview) method, explained by the Prehandle method we know this method includes the following aftercompletion The Interceptor method can only be called if the return value of the Prehandle method of the currently-owned class 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 returns 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, which is somewhat different from the Struts2 execution in interceptor. Struts2 inside the Interceptor execution process is also chained, but in Struts2 need to manually invoke the Actioninvocation invoke method to trigger the next interceptor or action call, Then the contents of each interceptor before the Invoke method call are executed in the order of Declaration, and the content after the Invoke 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.

Spring MVC 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.