spring boot关于静态资源
WebMvcAutoConfiguration.class
WebMvcAutoConfiguration下的WebMvcAutoConfigurationAdapter中有addResourceHandlers方法
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//如果已经配置自定义资源,则直接返回
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
//通过webjars的方式,在poem中导入webjars的依赖文件
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
/*获得静态资源的路径,通过getStaticPathPattern到Resources类可以看到路径,通过访问路径获取路径下的资源
private static final String[] CLASSPATH_RESOURCE_LOCATIONS =
new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
*/
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});
}
});
}
}
通过源码可知,在springboot中,可以使用以下方式处理静态资源
- 自定义方式
spring.mvc.static-path-pattern=
- 导入webjars依赖,localhost:8080/webjars/
- 访问以下路径:resources下的public,static,resources,优先级为resources>static(默认)>public
静态资源访问
只要静态资源放在类路径下的static、public、resources、META-INF/resources
访问:当前项目根路径/+静态资源名
例如:
访问:
测试 当静态资源名和动态请求名相同时
//@RestController即@Controller 和 @ResponseBody,返回return的数据,不返回页面
@RestController
public class IndexController {
@RequestMapping("/css.css")
public String page(){
return "aaaaa";
}
}
以上动态请求和静态资源请求都是css.css
测试结果:请求到动态资源
原理:静态映射/** 请求时先去找controller,如果controller不能处理,则请求静态资源处理器,静态资源也找不到则响应404
给静态资源加前缀
#增加前缀
spring:
mvc:
static-path-pattern: /static/**
访问:
默认没有前缀,这样相当于给静态资源加前缀,同时也解决了动态请求和静态请求名称冲突的情况。
http://localhost:8081/css.css 访问动态资源css.css
http://localhost:8081/static/css.css 访问静态资源css.css
改变默认的静态资源路径
默认路径:private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
改变路径:
#改变默认的静态资源路径
web:
resources:
static-locations: classpath:/aaa/
分类:
spring boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!