Dabio together to learn the fourth back of-SPRINGMVC (Interceptor use)

Source: Internet
Author: User
Tags truncated

I. Introduction of InterceptorsThe interceptor in the SPRINGMVC, in simple terms, isInterception of user requests, we can do it after the interception request.preprocessing and post-processing, you can do the logging, permission control, request calculation and other operations. And the filter in the Servlet API is a bit similar.
Second, the use of interceptors1. Writing interceptorsWe have to write the interceptor ourselves, the more commonly used method is to implement the Org.springframework.web.servlet.HandlerInterceptor class, I put this kind of source paste out, the internal on three methods, our business can be implemented in the method.
Package Org.springframework.web.servlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** Interceptor Interface, internal 3 methods **/public interface Handlerinterceptor {/**[call ago] Before the controller executes, calling this method returns true to continue execution, returning false abort execution here can join login checksum, permission intercept, etc. **/boolean Prehandle (httpservletrequest request, HttpServletResponse response, Object handler)    calls this method after the controller executes but does not return the view after the throws exception;/**[has been called but has not yet been rendered The model data can be processed before returning to the user, for example by adding common information to the page to display **/void Posthandle (httpservletrequest request, httpservletresponse response, Object handler, Modelandview Modelandview) throws exception;/**[call after the view has been rendered] the controller executes and calls this method after the view returns Here you can get exception information when the controller is executed here you can record the operation log, resource cleanup and other **/void aftercompletion (httpservletrequest request, HttpServletResponse Response, Object handler, Exception ex) throws Exception;}
OK, so let's try to write a class to implement it, first use the simple interceptor first. Let's look at the configuration and add some files below.
Interceptors:
Package Com.billstudy.springmvc.interceptor;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.web.servlet.handlerinterceptor;import org.springframework.web.servlet.modelandview;/** * Custom Interceptor * @author Bill * @since V1.0 2015/02/04 */public class Myinter Ceptor01 implements Handlerinterceptor {@Overridepublic Boolean prehandle (HttpServletRequest request, HttpServletResponse Response,object handler) throws Exception {System.out.println ("Myinterceptor01.prehandle ()"); return True;<span style= "White-space:pre" ></span>//returns true here, the request can go to the controller} @Overridepublic void Posthandle (httpservletrequest request, HttpServletResponse response,object handler, Modelandview Modelandview) throws Exception {System.out.println ("Myinterceptor01.posthandle ()");} @Overridepublic void Aftercompletion (httpservletrequest request,httpservletresponse response, Object handler, Exception ex) throws Exception {System.out.println ("MyintercePtor01.aftercompletion () ");}} 



Controller:
Package Com.billstudy.springmvc.controller;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.servlet.modelandview;/** * By requesting the internal Controller method, combined with the interceptor test effect * @author Bill * @since V1.0 2015/02/04 */@Controller @requestmapping ("/demo") public class Democontroller {@RequestMapping ("/demo01") public Modelandview demo01 (HttpServletRequest request, HttpServletResponse response) {System.out.println ("democontroller.demo01 ()"); Modelandview result = new Modelandview ("/demo"); Result.addobject ("msg", "I am the Moe's msg"); return result;}

demo.jsp
<% @page pageencoding= "UTF-8" contenttype= "text/html; Charset=utf-8 "%>


Springmvc-servlet.xml
<?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:mvc= "Http://www.springframework.org/schema/mvc" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/  Beans Http://www.springframework.org/schema/beans/spring-beans-3.1.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd Http://www.springframework.org/schema/context http ://www.springframework.org/schema/context/spring-context-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http ://www.springframework.org/schema/aop/spring-aop-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/http Www.springframework.org/schema/tx/spring-tx-3.1.xsd "><!--Auto Scanner class path--><context: Component-scan bAse-package= "Com.billstudy.springmvc"/><mvc:annotation-driven/><bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver "><property name=" prefix "value="/pages "/ > <property name= "suffix" value= ". jsp"/></bean> <mvc:interceptors><mvc:interceptor>< !--path= "/user/*.do"/user/all requests path= "/*/*" any two level request Path= "*" Invalid path= "/**" Any request--><mvc:mapping path= "/**"/&GT;&L T;bean class= "Com.billstudy.springmvc.interceptor.MyInterceptor01"/> </mvc:interceptor></mvc: Interceptors></beans>

OK, the following is deployed under the Tomcat test.

Console output:
What's the effect of this?
III. configuration and Operation process descriptionWhen we configured the Interceptor in Springmvc-servlet.xml earlier, we were the configured global interceptor, which means that all mapper requests were intercepted. Because we can configure multiple mapping. If you want to use an interceptor only for a single mapping, you can inject a interceptors attribute inside it by looking at the source code. We find in all mapping parent classes, that is, Org.springframework.web.servlet.handler.abstracthandlermapping, it has a list inside itInterceptors= new ArrayList () such a collection. So all mapping can inject the interceptor chain through it.
Let's say we just want a single mapping injection interceptor that can be configured like this:
<bean class= "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" ><property name= "< Span style= "color: #ff0000;" >interceptors</span> "><list><bean id=" HandlerInterceptor1 "class=" Springmvc.intercapter.HandlerInterceptor1 "/><bean id=" HandlerInterceptor2 "class=" Springmvc.intercapter.HandlerInterceptor2 "/><span style=" color: #ff0000; " >//... You can configure multiple, call </span></list></property></bean> in a configured order
The interceptor that configures the global is:
<mvc:interceptors><mvc:interceptor><!--path= "/user/*.do"  /user/all requests path= "/*/*" any two-level request Path= "* "Invalid   path="/** "arbitrary request   --><mvc:mapping path="/** "/><bean class=" Com.billstudy.springmvc.interceptor.MyInterceptor01 "/> </mvc:interceptor><span style=" color: #ff0000; " ><!--Here you can also configure multiple mvc:interceptor tags--></span></mvc:interceptors>

The following test, prehandle,posthandle,aftercompletion of the operating rules, we can write a few more interceptor to test.
After adding 2 interceptors, the configuration changes are as follows:
<mvc:interceptors><mvc:interceptor><mvc:mapping path= "/**"/><bean class= " Com.billstudy.springmvc.interceptor.MyInterceptor01 "/> </mvc:interceptor><mvc:interceptor>< Mvc:mapping path= "/**"/><bean class= "Com.billstudy.springmvc.interceptor.MyInterceptor02"/> </mvc: Interceptor><mvc:interceptor><mvc:mapping path= "/**"/><bean class= " Com.billstudy.springmvc.interceptor.MyInterceptor03 "/> </mvc:interceptor><!--You can also configure multiple MVC here: Interceptor Label--></mvc:interceptors>

Currently all interceptors are simple print run methods, and all Prehandler are returned true, then we take a look at the request. What is the order of the console printing?
We can see thatthe pre is called in the order in which it is configured. And Post,after is called in reverse order.。 There is no kind of recursive feeling, haha.
The following test will return the prehandler of interceptor to False, then the request is truncated after it is here, and the controller cannot be accessed. How does the interceptor work at this time? The modified code is as follows:
Package Com.billstudy.springmvc.interceptor;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.web.servlet.handlerinterceptor;import org.springframework.web.servlet.modelandview;/** * Custom Interceptor * @author Bill * @since V1.0 2015/02/04 */public class Myinter Ceptor02 implements Handlerinterceptor {@Overridepublic Boolean prehandle (HttpServletRequest request, HttpServletResponse Response,object handler) throws Exception {System.out.println ("Myinterceptor02.prehandle ()"); <strong><span style= "color: #cc0000;" >return false; This returns false, the request is truncated here! </span></strong&gt @Overridepublic void Posthandle (HttpServletRequest request, HttpServletResponse Response,object handler, Modelandview Modelandview) throws Exception {System.out.println ("Myinterceptor02.posthandle ()");} @Overridepublic void Aftercompletion (httpservletrequest request,httpservletresponse response, Object handler, Exception ex) throws Exception {System. Out.println ("myinterceptor02.aftercompletion ()");}} 

Run output:
Hey, what happened to the Interceptor 2 after and Interceptor 3 method input? Post seems to be missing, why is it? 1. First request in the order of the interceptor configuration, into the Interceptor 1 Prehandler method, this time return true, continue to execute 2. Prehandler in the Interceptor chain 2, where false is returned, and the request is coaxed home. Equivalent to Springmvc told it. You have been intercepted, the operation behind you can not be done, go back. Haha 3. At this time, the request of the Meng Da is no way, can only go home. But because it passes the Prehandler method of the Interceptor 1, the After method is executed. 4. As for the Interceptor 3, the request is not in contact at all, so and the Interceptor 3 all related methods are not executed.
After the request was coaxed back, because it did not arrive com.billstudy.springmvc.controller.DemoController.demo01(HttpServletRequest, HttpServletResponse) This method, so the value of MSG is also empty. That's what our page is actually:
Interceptor Three ways to run the conclusion: Prehandle called by Interceptor definition order
Posthandler by interceptor definition reverse Call
Aftercompletion by interceptor definition reverse Call


Posthandler all interceptors within the interceptor chain return to the successful call
Aftercompletion only Prehandle returns true to call

Okay, it's over here, will you use the interceptor? here is love life, Love technology, like to make friends of the big Puma. (PS: Recently overtime more up, update frequency not so fast, sorry ah.) Back home The whole people are a little dizzy. ^ _ ^) The current SPRINGMVC update is here to end, the project development is almost enough, the latter intends to write down MyBatis related.

Dabio together to learn the fourth back of-SPRINGMVC (Interceptor use)

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.