xml 方式
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean id="myHandlerInterceptor" class="controller.MyHandlerInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
public class MyHandlerInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("=====preHandle");
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("=====postHandle");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("=====afterCompletion");
}
}
这是 HandlerInterceptor 会被注册成 MappedInterceptor,在 RequestMappingHandlerMapping 执行 ApplicationContextAware 的 setApplicationContext 回去加载所有的 MappedInterceptor。这样 HandlerMapping 中就有了这个自定义的 Interceptor
+
![](https://i-blog.csdnimg.cn/blog_migrate/0d3af6336e3d922841d8a90e29604bdf.png)
annotation
可以使用 @EnableWebMvc 来注册 RequestMappingHandlerMapping,在注册时会去获取 interceptor。
![](https://i-blog.csdnimg.cn/blog_migrate/cd8cfc1d8dc0540b2943018a0d8cb087.png)
此时如果我们需要加入自己的 HandlerInterceptor 的话自己先实现 `WebMvcConfigurer` 这个接口,实现里面的 `addInterceptors` 方法,同时将这个实现类注册到容器中去。自己再去实现 HandlerInterceptor,跟上面的 `MyHandlerInterceptor` 一样。
在 springboot 中通过 `WebMvcAutoConfiguration` 这个配置类来注册 `RequestMappingHandlerMapping`,注册时加载 HandlerInterceptor 跟上面一样
![](https://i-blog.csdnimg.cn/blog_migrate/2b888e4e0d058b561d674213e6786c2d.png)
备注:`WebMvcAutoConfiguration` 这个配置类是通过 springboot 自动装配加载的。(spring.factories 中的 EnableAutoConfiguration)
QQ:
![](https://i-blog.csdnimg.cn/blog_migrate/aaf997f4f4fb89c2dfd97cd2a73a5083.png)
QQ 群
![](https://i-blog.csdnimg.cn/blog_migrate/80c8cc7f6f6a56768c9f21a3026c4b13.png)
微信:TY_3268407924
![](https://i-blog.csdnimg.cn/blog_migrate/985d59ce6c3135717136b07aba5b53bc.png)