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("**")不要使用 “/**”,否則靜態資源還是會被攔截


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM