默认的静态资源访问
当我们构建好Springboot项目后会发现项目路径下会有resources/static
文件夹,它就是默认存放静态资源的文件夹之一。
源码分析
WebMvcAutoConfiguration
匹配规则
静态资源存放路径
所以,静态资源的路径默认一共是有五个(优先级由上到下)
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/:斜杠表示的是/webapp目录
自定义静态资源访问路径
源码分析
由此我们可以分析:
可以通过配置文件中匹配其前缀名规则,即可自定义静态资源的访问路径与匹配规则。
例子
spring:
resources:
static-locations: classpath:/smallpineapple/
mvc:
static-path-pattern: /**
file:
uploadDir: /usr/static/img/
通过类添加自定义静态资源配置
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
@Value("file.uploadDir")
String uploadDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//匹配类路径下的smallpineapple目录下的所有静态资源
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/smallpineapple/");
//匹配指定目录的静态文件
registry.addResourceHandler("/**")
.addResourceLocations("file:///"+uploadDir);
}
}
最后补充
问:/**
和/*
有什么区别?
由于这是一种Ant风格的路径匹配符,
/**
表示可以匹配任意层级的路径,而/*
表示匹配当前层级下的任何路径。
例子:通过类进行自定义静态资源配置
http://localhost:8080/project/smallpineapple/1.img
http://localhost:8080/project/smallpineapple/img/1.img
上面这两个路径对访问1.img图片来说都是生效的,而如果
/*
则第二种无法访问。