前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >刨根问底:Spring Boot中HandlerInterceptor没有拦截静态资源问题

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

作者头像
大神带我来搬砖
发布2018-06-08 15:54:10
1.1K0
发布2018-06-08 15:54:10
举报
文章被收录于专栏:大神带我来搬砖

在Spring Boot中设置了HandlerInterceptor,发现对于js、css等文件都没有起作用。 定义一个HandlerInterceptor

代码语言:javascript
复制
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匹配到所有路径

代码语言:javascript
复制
@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。

代码语言:javascript
复制
@Configuration
public class WebConfig {

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.05.29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档