SpringBoot的静态资源处理
关于这个问题,总是有人访问不到
springboot
的静态资源。所以,我把我熟悉的处理方法写出来。不对的地方,还望指教。
SpringBoot的版本(撰写本文时最新版本)
2.1.2.RELEASE
application.yml 配置
spring:
mvc:
static-path-pattern: /static/**
resources:
static-locations:
- classpath:/static/
- file:D:\\static
spring.mvc.static-path-pattern
配置的是,访问静态资源的uri
spring.resources.static-locations
配置的是一个或者多个静态资源路径(文件夹)
- 可以是
classpath
目录下的资源,使用classpath:
开头 - 可以是本地目录下的资源,使用
file:
开头
- 可以是
程序配置方式
其实我几乎没使用过这种方式,都是采用配置文件的方式来设置静态资源的映射
SpringBoot2.x
建议实现接口WebMvcConfigurer
来处理mvc
相关的配置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.addResourceLocations("file:D:/static/");
}
访问classpath资源
访问本地目录资源
拦截器会拦截静态资源
如果拦截器的拦截规则是 /**
,也就是拦截所有的请求,那么也会拦截到静态资源的请求
处理办法
// 读取到配置里面的静态资源访问路径
@Value("${spring.mvc.static-path-pattern}")
private String staticPathPattern;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
System.out.println("拦截:" + request.getRequestURI());
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}).addPathPatterns("/**").excludePathPatterns(this.staticPathPattern); // 当拦截所有请求时,排除掉静态资源的uri
}
请求静态资源,没有发生拦截
如果你有更好的方法,欢迎告诉我。
最后
你现在知道咋处理静态资源了么?能力一般,水平有限,不正的地方还望指出。