What is an interceptor
Interceptor: SpringMVC, Struts and other presentation layer framework itself, does not intercept JSP/HTML/CSS /image access, only the access controller method (Handler). The underlying idea is AOP
- In terms of configuration, serlvet, filter, listener are configured in web.xml, while interceptor is configured in the configuration file of the presentation layer framework
- Intercepts the Handler business logic once before it executes
- Intercept once before the Handler logic completes but does not jump to the page
- Intercept once after the jump page
Configure a custom interceptor
-
Implement the HandlerInterceptor interface
-
Override method:
- PreHandle: executes before handler, returns true to permit (executes as long as the interceptor is accessed)
- PostHandle: Handler logic is actually executed but not yet returned to the page (executed if the page is cleared)
- AfterCompletion: After returning to the page (which must be executed whenever the interceptor is accessed)
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor 1: preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println(Interceptor 1: postHandle);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Interceptor 1: afterCompletion"); }}Copy the code
- Springmvc.xml configures the interceptor
<mvc:interceptors>
<mvc:interceptor>
<! --/** Intercepts all browser requests -->
<mvc:mapping path="/ * *"/>
<! -- You can configure the specified resources to be released without blocking.
<mvc:exclude-mapping path="/js/**"></mvc:exclude-mapping>
<mvc:exclude-mapping path="/css/**"></mvc:exclude-mapping>
<mvc:exclude-mapping path="/image/**"></mvc:exclude-mapping>
<bean id="myInterceptor " class="com.kehao.interceptor.MyInterceptor "></bean>
</mvc:interceptor>
</mvc:interceptors>
Copy the code
Multiple interceptors
If you have multiple interceptors
preHandle
Methods need to be executed according to the configuration order in SpringMVC.xmlafterCompletion
On the contrary, the sooner it is implementedpreHandle
Method of interceptor, the later the executionafterCompletion
, similar to the stack