SpringBoot关于默认静态资源访问路径定义及自定义设置
Spring Boot 对静态资源映射提供了默认配置, 默认将 /** 所有访问映射到以下目录:
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources
classpath 即WEB-INF下面的classes目录,在springboot项目中可能就是src/main/resources目录。
也就是\resources目录下默认上面三个目录:static,public,resources均可以无需任何配置浏览器直接访问到。
正常情况下,我们只需要将我们的静态资源放到src/main/resource/static这个目录下即可正常访问,也不需要额外再去创建其他静态资源目录,但是如果我们想自定义一下目录,则可以在application.properties添加spring.resources.static-locations:来指定位置
spring.resources.static-locations:的默认值是:
classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
如果我们想将html页面资源放在src/main/resource/webapp下,只需设置spring.resources.static-locations=classpath:/webapp/,即可直接访问到,但是会覆盖前面的四条设置。所以直接在后面追加一条即可。
像这样:
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/
当然你也可以直接指定一个硬盘上的任意目录:
#自定义的属性,指定了一个路径,注意要以/结尾 upload-path=D:/verifies/ #会覆盖默认配置,所以需要将默认的也加上否则static、public等这些默认静态资源路径将不能再被使用 spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/,file:${upload-path}
当然也可以通过代码在java类中指定,一般不推荐,配置文件指定更加简单高效
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if(!registry.hasMappingForPattern("/static/**")){ registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } super.addResourceHandlers(registry); } }
本文来自博客园,作者:IT情深,转载请注明原文链接:https://www.cnblogs.com/wh445306/p/16751730.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!