解读静态资源访问static-locations和static-path-pattern
静态资源访问static-locations和static-path-pattern
静态资源配置底层源码
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
//配置访问地址为/webjars/**时,去/META-INF/resources/webjars文件夹下寻找资源
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
}
静态资源默认前缀:
private String staticPathPattern = "/**";
静态资源默认地址:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
/**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;静态资源目录

如果每个目录下面都有相同的文件,那么访问的优先级为 META-INF>resources>static>public
静态资源访问前缀(默认无前缀)可以使用下面的yaml内容来设置
spring:
mvc:
static-path-pattern: /liang/** //会导致欢迎页和favicon.ico失效静态资源存放地址(静态文件只能存放在文件夹yuan里面)
spring:
web:
resources:
static-locations: classpath:/yuan/当配置文件如下
spring
web:
resources:
static-locations: classpath:/yuan/
mvc:
static-path-pattern: /liang/**
可以直接通过地址 http://localhost:8080/liang/a.png 直接进行访问,查看到想要结果
当静态访问前缀为/**时,静态资源目录下有一个a.png,controller控制层的@RequestMapping("/a.png")。

得到结果

结论:请求进来,先去controller看能不能处理,不能处理的所有请求又都交给静态资源处理器。静态资源找不到就报404
为什么欢迎页(index.html)有静态资源访问前缀就不能访问了

通过 http://localhost:8080/liang/index.html可以直接访问到界面,但是通过 http://localhost:8080/liang 或者 http://localhost:8080/ 都不能直接访问到index。
但是如果把静态资源访问前缀去除,就可以通过 http://localhost:8080/ 访问到index.html了.
这是因为底层做了处理

实现WebMvcConfigurer接口
会把自定义配置加载到默认的配置中
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("访问的路径").addResourceLocations("资源的路径");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
}配置文件中静态资源目录为


可以简单理解为:实现WebMvcConfigurer接口,可以把自己自定义的一些配置加载到系统的默认配置中
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
详解spring cloud config整合gitlab搭建分布式的配置中心
这篇文章主要介绍了详解spring cloud config整合gitlab搭建分布式的配置中心,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-01-01
IntelliJ IDEA设置代码的快捷编辑模板Live Templates
今天小编就为大家分享一篇关于IntelliJ IDEA设置代码的快捷编辑模板Live Templates,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2018-10-10
springboot如何使用yml文件方式配置shardingsphere
这篇文章主要介绍了springboot如何使用yml文件方式配置shardingsphere问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-09-09


最新评论