在使用SpringBoot做项目时,需要使用拦截器判断用户是否登陆,来决定用户是否能访问某些页面。
起初,通过继承来WebMvcConfigurerAdapter来注册拦截器,但是由于SpringBoot 2.0之后,就将WebMvcConfigurerAdapter废弃使用了,推荐使用WebMvcConfigurationSupport,但是使用WebMvcConfigurationSupport后发现网页不能获取到静态资源。
例如:
swagger-ui 接口文档无法访问 doc.html接口文档无法访问
Swagger问题:No mapping for GET /swagger-ui.html
历史配置:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.*;
@SpringBootConfiguration
public class AdminLoginAdapter extends WebMvcConfigurerAdapter {
@Autowired
AdminLoginInterceptor adminLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin").excludePathPatterns("/login/**");
registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/index");
super.addInterceptors(registry);
}
这里提供两种解决方法:
package com.donglei.myblog.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.*;
@SpringBootConfiguration
public class AdminLoginAdapter extends WebMvcConfigurationSupport {
@Autowired
AdminLoginInterceptor adminLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin").excludePathPatterns("/login/**");
registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/index");
super.addInterceptors(registry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//重写这个方法,映射静态资源文件
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/");
super.addResourceHandlers(registry);
}
}
实践证明,这种方法行之有效,但是有的朋友可能表示,这种方法还是有问题,那就第二种方法,实现WebMvcConfigurer接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.*;
@SpringBootConfiguration
public class AdminLoginAdapter implements WebMvcConfigurer {
@Autowired
AdminLoginInterceptor adminLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin").excludePathPatterns("/login/**");
registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/index");
//super.addInterceptors(registry);
}
}
这样,就解决了WebMvcConfigurationSupport 静态资源失效问题
https://www.leftso.com/article/2408310944466088.html