本文主要是介绍springboot 静态资源拦截配置 及加上 /static/** 路径放行无效的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
两个属性spring.mvc.static-path-pattern和spring.resources.static-locations
spring.mvc.static-path-pattern:/** (这是源码中的默认值)//设置为/static/**的话 需要在url中请求资源时需要加上/static/才能正常访问,//不设置也可以正常访问
源码如图:
spring.resources.static-locations= //(设置静态资源的目录,默认值见下图)
springboot会自动按照默认值的顺序优先级查找这几个目录下的静态资源
源码如图:
public static class Resources {private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};private String[] staticLocations;private boolean addMappings;private boolean customized;private final WebProperties.Resources.Chain chain;private final WebProperties.Resources.Cache cache;public Resources() {this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;this.addMappings = true;this.customized = false;this.chain = new WebProperties.Resources.Chain();this.cache = new WebProperties.Resources.Cache();}
//编写了一个拦截器类并重写了preHandle方法
public class LoginHandlerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object loginUser = request.getSession().getAttribute("loginUser");if (loginUser==null){request.setAttribute("msg","用户不存在请重新登录");request.getRequestDispatcher("/index.html").forward(request,response);return false;}else {return true;}}
}
//将拦截器通过注解交给容器管理
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {/*添加Controller映射*/@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("/index");registry.addViewController("/index.html").setViewName("/index");registry.addViewController("/main.html").setViewName("/dashboard");}/*添加拦截器*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {String[] str = {"/index.html", "/", "/user/login","/static/**"};registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns(str); //注意排除静态资源路径}
str = {"/index.html", "/", "/user/login","/static/**"}这里 直接添加"/static/**"的话我这里没有生效,因为上面有静态资源目录的默认配置,请求到拦截器这里的时候 springboot还没有将/static/加载到路径上去,没有加载拦截器识别不到,所以没有生效依然访问不到静态资源
由于/static/是由springboot自动装载的,拦截器这里想要/static/**路径放行生效的话,可以显式在properties或者yml文件定义
spring.mvc.static-path-pattern=/static/**
, 或者不定义,在中间加一个显式的文件夹目录(这里命名assert)将静态资源都放入这个中间目录下 拦截器就能识别到了
然后上面str = {"/index.html", "/", "/user/login","/static/**"}中的/static/**修改成/assert/**就可以生效了 达到显式定义static-path-pattern同样的效果
这篇关于springboot 静态资源拦截配置 及加上 /static/** 路径放行无效的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!