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

相关推荐
吃汉堡吃到饱1 小时前
【Android】浅析MVC与MVP
android·mvc
一颗知足的心2 小时前
SpringCloud Alibaba五大组件之——Sentinel
spring·spring cloud·sentinel
wang_book5 小时前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
一个诺诺前行的后端程序员7 小时前
springcloud微服务实战<1>
spring·spring cloud·微服务
Tatakai2511 小时前
Mybatis Plus分页查询返回total为0问题
java·spring·bug·mybatis
哆木12 小时前
部署在线GBA游戏,并通过docker安装启动
游戏·html·gba
掐指一算乀缺钱12 小时前
SpringBoot 数据库表结构文档生成
java·数据库·spring boot·后端·spring
bug菌¹13 小时前
滚雪球学SpringCloud[4.2讲]: Zuul:Netflix API Gateway详解
spring·spring cloud·gateway
小哇66613 小时前
spring-TransactionTemplate 编程式事务
数据库·spring
丶重明14 小时前
【2024】前端学习笔记3-外部链接-内部链接-锚点链接
html