刨根問底:Spring Boot中HandlerInterceptor沒有攔截靜態(tài)資源問題

在Spring Boot中設(shè)置了HandlerInterceptor,發(fā)現(xiàn)對(duì)于js、css等文件都沒有起作用。
定義一個(gè)HandlerInterceptor

public class FooInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("foo");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}

將HandlerInterceptor匹配到所有路徑

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FooInterceptor())
                .addPathPatterns("/**");

    }

}

這時(shí)雖然PathPatterns設(shè)置了“/**”,但是發(fā)現(xiàn)FooInterceptor對(duì)靜態(tài)資源沒有起作用。這時(shí)看看addInterceptors方法上的注釋。

Add Spring MVC lifecycle interceptors for pre- and post-processing of controller method invocations. Interceptors can be registered to apply to all requests or be limited to a subset of URL patterns.
Note that interceptors registered here only apply to controllers and not to resource handler requests. To intercept requests for static resources either declare a MappedInterceptor bean or switch to advanced configuration mode by extending WebMvcConfigurationSupport and then override resourceHandlerMapping.

說明它只對(duì)controller起作用,如果想對(duì)靜態(tài)資源起作用,簡(jiǎn)單的方法是添加一個(gè)MappedInterceptor bean。

@Configuration
public class WebConfig {

    @Bean
    public MappedInterceptor getMappedInterceptor() {
        return new MappedInterceptor(new String[] { "/**" }, new FooInterceptor());
    }
}

參考代碼見https://github.com/kabike/spring-boot-demo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容