刨根问底: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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值