spring MVC是如何找到html文件并返回的?

Spring MVC 搜索路径

启动一个SpringBoot项目时,访问http://localhost:8080,对于SpringMVC,它会默认把这段url看成http://localhost:8080/index.html,所以这两个url是等价的。

.html, .css, .js, .img ...都是静态资源文件,不是通过controller访问的,而是spring mvc有一个静态资源搜索路径,在spring boot中,是位于org.springframework.boot.autoconfigure.web.ResourceProperties类下

java 复制代码
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
"classpath:/META-INF/resources/",
 "classpath:/resources/", 
"classpath:/static/",
 "classpath:/public/"};

classpath表示类路径,项目编译后,会有一个classes文件,这个文件夹下就是类路径。

spring MVC会按顺序依次搜索/META-INF/resources/、/resources/、/static/、/public/文件夹,先搜到指定的静态资源,就直接返回,不会继续搜下去。

这里,静态资源搜索路径中有两个index.html。

根据先来后到的原则,由于 "classpath:/resources/"定义在"classpath:/static/"前面,所以搜索到classpath:/resources/"下的index就会返回。

自定义静态资源搜索路径

当然,Spring MVC静态资源搜索路径可以自定义,在application.yaml文件中配置:

yaml 复制代码
spring:
  resources:
    static-locations: classpath:/custom

注意:

自定义的classpath:/custom这个路径并不会覆盖已经写死的静态资源访问路径,也就是前面几个路径依然生效。但是classpath:/custom是排在前面几个路径的前面的。

相关推荐
葡萄城技术团队8 分钟前
HTML元素单元格:用自定义 CellType 扩展 SpreadJS 的显示能力
前端·javascript·html
gaolei_eit14 小时前
Java+Ai+vue
java·spring·maven
玉&心14 小时前
关于配置mcp服务端sse-message-endpoint和sse-endpoint的注意点
spring·springai·mcp
蚰蜒螟16 小时前
一次 Spring AOP 与定时任务引发的死锁排查实录
java·spring·firefox
Java爱好狂.16 小时前
Java就业需要学习哪些内容?
spring·程序员·springboot·架构师·java面试·java面试题·java八股文
listening77717 小时前
HarmonyOS 6.1 元服务深度优化:从“秒开”到“常驻”的极致体验
java·开发语言·spring
空中湖1 天前
Spring AI Agent 编排:ReAct 模式 + 多 Agent 协作实战
人工智能·spring·react.js
shandianchengzi1 天前
【开源工具】我做了一个周深歌曲淘汰赛生成器:挑选 128 首歌 PK,选出你的年度 TOP1
html·音乐·网页·世界杯
触底反弹1 天前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html