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

相关推荐
java1234_小锋39 分钟前
Java高频面试题:Spring-AOP通知和执行顺序?
java·开发语言·spring
woniu_buhui_fei2 小时前
Spring Cloud Alibaba相关知识总结
spring
NE_STOP3 小时前
SpringCloud微服务进阶-Nacos更加全能的注册中心
spring
jessecyj3 小时前
maven导入spring框架
数据库·spring·maven
小江的记录本3 小时前
【Redis】Redis常用命令速查表(完整版)
java·前端·数据库·redis·后端·spring·缓存
卓怡学长3 小时前
m281基于SSM框架的电脑测评系统
java·数据库·spring·tomcat·maven·intellij-idea
Densen20143 小时前
企业H5站点升级PWA (二)
java·后端·spring
marsh02063 小时前
16 openclaw与数据库集成:ORM使用与性能优化
数据库·spring·ai·性能优化·编程·技术
毕设源码-赖学姐4 小时前
【开题答辩全过程】以 基于.NET MVC的婚庆服务系统设计为例,包含答辩的问题和答案
mvc·.net
进击的野人4 小时前
从AI“说人话”到“说结构话”:Spring AI结构化输出实战解析
人工智能·spring·ai编程