Spring Boot访问index.html踩坑纪

时间:2024-05-21 19:53:05

使用环境 Spring Boot 1.5.10.RELEASE
该版本下欢迎页(index.html)存放的路径?
在IDEA中,使用ctrl+n搜索WebMvcAutoConfiguration,然后在该类下分析源码。在此过程中,我们可以使用ctrl+鼠标左键实现跳转。
Spring Boot访问index.html踩坑纪

从上图分析得知,该版本下欢迎页存放的路径如下:

“classpath:/META-INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”,
“classpath:/” 当前项目的根路径

其中,classpath是指类路径下,使用maven管理项目时,classpath是指javaresources目录下。
Spring Boot访问index.html踩坑纪
之后,由于好奇心,我把index.html放到templates目录下。结果可想而知,无法访问到index.html页面。
Spring Boot访问index.html踩坑纪
但是,一次我在查阅Spring Boot 2.1.5.RELEASE版本时,发现
Spring Boot访问index.html踩坑纪
Spring Boot同时支持静态和模板化欢迎页面。它首先在配置的静态内容位置中查找index.html文件。如果没有找到,则查找索引模板(templates目录下)。如果找到其中之一,它将自动用作应用程序的欢迎页面。
所以,使用该版本时,我们可以将index.html放在templates目录下,启动项目时,我们在浏览器直接访问localhost:端口号即可请求到index.html页面。