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是排在前面几个路径的前面的。

相关推荐
独泪了无痕2 小时前
SpringBoot Event事件机制,轻松实现业务解耦
spring boot·后端·spring
小鹿的周先生2 小时前
Spring-AI-第2篇-ChatClient 实战:使用 DeepSeek 完成第一次 AI 对话
java·人工智能·spring
程序员黎剑5 小时前
Spring-Bean生命周期-构造器访问Autowired字段为null
java·后端·spring
xy34536 小时前
Axure9.0 中继器遮罩的核心应用场景(精准适配列表交互)
前端·ui·html·原型·产品设计·axure9.0
Data_Journal7 小时前
Scrapyd:分步教程
开发语言·python·microsoft·golang·编辑器·html·iphone
SQL-First布道者8 小时前
⚡Spring JDBC 完整体系 · 第 10 集 · 手搓 `BaseCondition`
java·spring boot·后端·spring·mybatis·spring jdbc
labixiong9 小时前
button按钮原生开关弹窗,零 JS 搞定80%交互场景
前端·javascript·html
霸道流氓气质10 小时前
Spring AI Function Calling实现原理与自定义函数
java·spring·microsoft
gs8014010 小时前
Spring AI × Nacos 3.2:打造可动态治理 Prompt 的电商售后智能 Agent
人工智能·spring·prompt
降临-max12 小时前
Selenium(HTML+JavaScript&DOM+Selenium IDE)
自动化测试·selenium·测试工具·html