这是我参与8月更文挑战的第26天,活动详情查看:8月更文挑战
导入静态资源
WebMVCConfiguration.class
找到addResourceHandler方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//判断静态资源是否已自动配置
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl =this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
// 判断资源是否配置到一下路径,如果没有,设置到该路径
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
// 获取静态资源的路径
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
访问webjar目录,通过maven引入的jar包都是这种方式
/webjars/就是下面的缩写 classpath:/META-INF/resources/webjars/
-
获取项目静态资源路径
this.mvcProperties.getStaticPathPattern();
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//这句话在点进getStaticPathPattern();方法后
// /** 当前目录下的所有文件都识别,即资源目录
private String staticPathPattern = "/**";
// 被识别的目录,第一个就是上面那个jar报的
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/" , "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
剩下三个:对应资源目录下的三个文件夹(可手动创建)
总结
通过源码,我们知道处理静态资源
- webjar 第三方jar包 访问路径:localhost:8080/webjar/文件名
- public,static,resources 三个目录下的文件 访问路径:lovalhost:8080/文件名
优先级:resource > static(默认) > public