亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

如何使用 SpringMVC 中的攔截器?

標簽:
Java Spring 源碼

  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)

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
JAVA開發工程師
手記
粉絲
2
獲贊與收藏
0

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消