步骤 1 彻底搞定静态资源
先找到这个类:WebMvcAutoConfiguration,在这个jar包里面,还是自动配置
WebMvcAutoConfiguration中有一个 addResourceHandlers 方法,这是自动配置静态资源目录的。
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
registration.addResourceLocations(new Resource[]{resource});
}
});
}
}
先看这个:
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
}
如果isAddMappings为false,就打印默认资源映射路径失效了。isAddMappings方法其实就是返回一个addMappings变量(在WebProperties中)
addMappings的含义就是运行访问静态资源,如果你设置成false,就是禁用所有静态资源映射。
站长在写这篇教程的时候,用的SpringBoot版本为2.5.1,是目前最新的版本。发现和之前的版本比起来,改动还是很大的。翻源码很麻烦,我就直接告诉你结论就行了。
默认的静态资源目录是:
new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
这点和以前是一样的,测试一下
访问什么路径能返回public.js呢?
在WebMvcProperties中,有一个staticPathPattern属性。
默认就是/**,所以,无论你访问什么,都可以被静态资源处理器接受。
启动项目,访问http://localhost:8888/public.js
[图片上传失败…(image-1fcffe-1625294071735)]
成功访问,现在我们手动添加一个静态目录。
spring:
profiles: test
resources:
static-locations: [classpath:/my/]
访问http://localhost:8888/my.txt,也成功了。
最后,把静态资源开关关掉。
spring:
profiles: test
resources:
static-locations: [classpath:/my/]
add-mappings: false
这样就访问不到任何静态资源了,不过一般来说不用关。
转载自:http://java18.cn/
标签:
spring
, spring boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)