4.2 静态资源访问
Spring Boot 中对于SpringMVC 的自动化配置都在WebMvcAuto Configuration 类中,在WebMvcAutoConfiguration 类中有一个静态内部类WebM vcAutoConfigurationAdapter , 实现
了WebMvcConfigurer 接口。
WebMvcConfigurer 接口中有一个方法addResourceHandlers,是用来配置静态资源过滤的。
public void addResourceHandlers(ResourceHandlerRegistry registry) { ... String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { custornizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations( this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)) .setCacheControl(cacheControl)); } }
staticPathPattern 默认定义在WebMvcProperties 中,定义内容如下:
private String staticPathPattern = "/**",
this.resourceProperties.getStaticLocations() 获取到的默认静态资源位置定义在ResourceProperties
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { ”classpath:/META-INF/resources/”,”classpath:/resources/”, ”classpath:/static/”,”classpath:/public/”};
在一个新创建的Spring Boot 项目中, 添加了spring-boot-starter-web 依赖之后, 在resources 目录下分别创建4 个目录, 4 个目录中放入同名的静态资源
此时, 在浏览器中输入“ http://localhost: 8080/p 1. png ”即可看到classpath:/META-INF /resources/目录下的p1.png,如果将classpath :/META-INF /resources/目录下的p1.png 删除,就会访问到classpath: /resources/目录下的p1.png,以此类推。
如果开发者使用IntelliJ IDEA 创建Spring Boot 项目, 就会默认创建出classpath:/static/ 目录,
静态资源一般放在这个目录下即可。
4.2.2. 自定义策略
方法1. 在自己置文件中定义
可以在appIication.properties中直接定义过滤规则和静态资源位置
spring.mvc.static-path-pattern = /static/** spring.resources.static-locations=classpath:/static/
过滤规则为 /static/**, 静态资源位置为 classpath:/static/。
重新启动项目, 在浏览器中输入“ http://localhost:8080/static/p1.png ” ,即可看到classpath :/static/目录下的资源。
如果修改成这个样子那么,在浏览器中输入“ http://localhost:8080/p1.png ” ,即可看到classpath :/static/目录下的资源。
spring.mvc.static-path-pattern = /** spring.resources.static-locations=classpath:/static/
方法2. Java 编码定义
只需要实现WebMvcConfigurer 接口即可, 然后实现该接口的addResourceHandlers 方法
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); }
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY