The controller layer interceptor inherits from the Handlerinterceptoradapter
The Handlerinterceptoradapter.java code is as follows
Public Abstract classHandlerinterceptoradapterImplementsHandlerinterceptor { Public BooleanPrehandle (HttpServletRequest request, httpservletresponse response, Object handler)throwsException {return true; } Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Modelandview Modelandview) throwsException {
} Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object handler, Exception ex)throwsException {
} }
The spring interceptor implements a controller interception by overriding these three methods.
Public classControllerinterceptorextendsHandlerinterceptoradapter { Public BooleanPrehandle (httpservletrequest request,HttpServletResponse response, Object handler)throwsException {System.out.println ("Controllerinterceptor.prehandle ()"); return true;} Public voidPosthandle (httpservletrequest request,httpservletresponse Response, Object handler,Modelandview Modelandview)throwsException {System.out.println ("Controllerinterceptor.posthandle ()");} Public voidaftercompletion (httpservletrequest request,httpservletresponse Response, Object handler, Exception ex)throwsException {System.out.println ("Controllerinterceptor.aftercompletion ()");}}
Configuring interceptors
<BeanID= "Handlermapping"class= "Org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">< Propertyname= "Interceptors"><List><refBean= "Controllerinterceptor" /></List></ Property>< Propertyname= "Mappings"><Props><propKey= "/hao/hello.do">Helloworldcontroller</prop></Props></ Property></Bean> <BeanID= "Controllerinterceptor"class= "Com.web.spring.mvc.interceptor.ControllerInterceptor"/>
Test Code Helloworldcontroller.java
@Controller @requestmapping ("/hao") Public class = "/hello") public String Hello (httpservletrequest request, HttpServletResponse Response) {System.out.println ("Hello"); return "HelloWorld"; }}
Description
Initiate the request, go into the interceptor chain, run the Prehandle method of all interceptors,
1. When the Prehandle method returns False, the Aftercompletion method of all interceptors is executed back from the current interceptor before exiting the interceptor chain.
2. When the Prehandle method is all true, execute the next interceptor until all interceptors are executed. Run the intercepted controller again. Then go into the interceptor chain, run the Posthandle method of all interceptors, and execute the Aftercompletion method of all interceptors back from the last interceptor.
When an interceptor throws an exception, the Aftercompletion method of all interceptors is executed back from the current interceptor
SPRINGMVC's Interceptor