-
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
-
annotation
可以使用 @EnableWebMvc 来注册 RequestMappingHandlerMapping,在注册时会去获取 interceptor。
此时如果我们需要加入自己的 HandlerInterceptor 的话自己先实现 WebMvcConfigurer
这个接口,实现里面的 addInterceptors
方法,同时将这个实现类注册到容器中去。自己再去实现 HandlerInterceptor,跟上面的 MyHandlerInterceptor
一样。
在 springboot 中通过 WebMvcAutoConfiguration
这个配置类来注册 RequestMappingHandlerMapping
,注册时加载 HandlerInterceptor 跟上面一样
备注:WebMvcAutoConfiguration
这个配置类是通过 springboot 自动装配加载的。(spring.factories 中的 EnableAutoConfiguration)
点击查看更多内容
为 TA 点赞
0 评论
共同学习,写下你的评论
暂无评论
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦