springboot 2.0+ 自定义拦截器 静态资源问题

之前项目的springboot自定义拦截器使用的是继承WebMvcConfigurerAdapter重写常用方法的方式来实现的.静态文件不需要进行放行,springboot会自动帮你放行。

springboot2.0之后如果想要自定义的话就不可以了,需要手动放行静态资源。此处我是实现了WebMvcConfigurer来自定义拦截器(根据需求也可以继承WebMvcConfigurationSupport,此处不再赘述)。下面是实现代码

@Configuration
public class MyMvcConfig implements  WebMvcConfigurer {

    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurer webMvcConfigurer(){
        WebMvcConfigurer adapter = new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }

            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("**")
                        .excludePathPatterns("/index.html","/","/hello1","/user/login")
                        .excludePathPatterns("/static/**");
            }
        };
        return adapter;
    }

}

注意:(大坑)此处的addPathPatterns("")不要使用 “/”,否则静态资源还是会被拦截

你可能感兴趣的:(springboot 2.0+ 自定义拦截器 静态资源问题)