Spring Boot 攔截器的坑——靜態資源404

Spring Boot使用攔截器時會遇到靜態資源404的坑

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor())
                .addPathPatterns("/api/sign/list")
                .addPathPatterns("/api/sign/scan")
                .addPathPatterns("/api/trainapply/person/list");
    }
}

代碼這樣寫會使Spring Boot不會加載靜態資源攔截器,所有我們應該用代碼配置Spring Boot的靜態資源攔截器,代碼:

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor())
                .addPathPatterns("/api/sign/list")
                .addPathPatterns("/api/sign/scan")
                .addPathPatterns("/api/trainapply/person/list");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/static/");
    }
}

我們實現WebMvcConfigurer這個接口就可以同時配置攔截器和靜態資源位置,這樣就解決了靜態資源404的問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章