默認的靜態資源訪問
當我們構建好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圖片來說都是生效的,而如果
/*
則第二種無法訪問。