Spring Boot2.0+中遇到的坑(一)自定义配置类扩展springMVC的功能

在spring boot1.0+,我们可以使用WebMvcConfigurerAdapter来扩展springMVC的功能,其中自定义的拦截器并不会拦截静态资源(js、css等)。

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //浏览器发送 /atguigu 请求来到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @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","/","/user/login");
            }
        };
        return adapter;
    }
    @Bean
    public LocaleResolver localeResolver(){

        return new MyLocaleResolver();
    }

}

在spring boot2.0+以后,WebMvcConfigurerAdapter就过时了,目前通过继承WebMvcConfigurationSupport类(ps:继承后好像MVC自动配置不生效了)或者实现WebMvcConfigurer接口来扩展springMVC的功能。然而该版本自定义的拦截器会拦截静态资源,因此在使用spring2.0+时,配置拦截器之后,我们要把静态资源的路径加入到不拦截的路径之中。

@Configuration
public class MyMvcConfig implements 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) {
            //将静态资源排除在拦截之外
            registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                    .excludePathPatterns("/index.html","/","/user/login","/static/**");
        }
        @Bean
        public LocaleResolver localeResolver(){
            return new MyLocaleResolver();
        }

}

 

你可能感兴趣的:(学习Spring,Boot遇到的坑,Spring,Boot)