思考:静态资源过滤这个问题 在maven规定的是 约定大于配置 ,所以src目录下的配置文件扫描不到,需要在pom.xml中添加过滤,那么springboot 需要不呢?
静态资源
在 SpringBoot项目中,默认是没有webapp文件夹 webapp文件夹的
如果你在创建项目时有添加 web的依赖,那它本身就是一个 web项目。
那问题也就接踵而至,没有web文件夹 我们的静态资源应该放哪里呢。
我们将项目结构展开,扫一眼 猜测的话应该是放到这两个文件夹中。
思考:我们在ssm项目中要配置pom过滤 那这里呢?就要看源码啦!
在WebMvcAutoConfiguration 自动配置类中找到这个
拿到源码
@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();
// webjars 配置
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));
}
}
大概意思就是:读一下源代码:比如所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源; springboot自动帮我们做了资源过滤处理
这是自动配置的静态资源 我们还可以自己定制
自定义路径
自定义路径很好理解,就是通过配置文件的形式 对静态资源加载路径进行自定义操作
/**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
这是存在于自动配置类中的属性(也就是我们可以配置的配置项)。
我们可以通过的 spring.resources.static-locations=来对静态资源加载路径进行配置,一旦配置后 默认的静态资源加载路径就会失效。SpringBoot会以我们配置的路径为准。(默认的路径下面会说)
一般和spring.mvc.static-Path-Pattern=配合使用,下面的代码为yaml格式,实际上二者并无太多差别。
默认路径
关于默认路径有哪些,我们可以通过在配置文件中点进 static-locations一探究竟
- /META-INF/resources/
- /resources/
- /static/
- /public/
- /**(假装有五个)
静态资源的默认访问优先级:
/META-INF/resources/>/resources/>/static/>/public/