刨根问底:Spring Boot中HandlerInterceptor没有拦截静态资源问题

在Spring Boot中设置了HandlerInterceptor,发现对于js、css等文件都没有起作用。 定义一个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("/**");

    }

}

这时虽然PathPatterns设置了“/**”,但是发现FooInterceptor对静态资源没有起作用。这时看看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.

说明它只对controller起作用,如果想对静态资源起作用,简单的方法是添加一个MappedInterceptor bean。

@Configuration
public class WebConfig {

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

参考代码见https://github.com/kabike/spring-boot-demo

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区