springmvc HandlerInterceptor

  1. 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

+

  1. annotation

可以使用 @EnableWebMvc 来注册 RequestMappingHandlerMapping,在注册时会去获取 interceptor。

此时如果我们需要加入自己的 HandlerInterceptor 的话自己先实现 `WebMvcConfigurer` 这个接口,实现里面的 `addInterceptors` 方法,同时将这个实现类注册到容器中去。自己再去实现 HandlerInterceptor,跟上面的 `MyHandlerInterceptor` 一样。

在 springboot 中通过 `WebMvcAutoConfiguration` 这个配置类来注册 `RequestMappingHandlerMapping`,注册时加载 HandlerInterceptor 跟上面一样

备注:`WebMvcAutoConfiguration` 这个配置类是通过 springboot 自动装配加载的。(spring.factories 中的 EnableAutoConfiguration)

QQ:

QQ 群

微信:TY_3268407924

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值