Spring Boot 2.7.1 官方文档里对其 Welcome Page 欢迎页功能有如下描述:
1.1.5. Welcome Page
Spring Boot supports both static and templated welcome pages. It first looks for an
index.html
file in the configured static content locations. If one is not found, it then looks for anindex
template. If either is found, it is automatically used as the welcome page of the application.Spring Boot 支持静态和模板化欢迎页面。它首先查找配置在静态内容位置中的 index.html。如果没有找到,它会查找 index 模板。如果找到其中一个,它将自动用作应用程序的欢迎页面。
配置在静态内容位置中的 index.html
静态内容位置在哪?同样看官方文档:
1.1.4. Static Content
By default, Spring Boot serves static content from a directory called
/static
(or/public
or/resources
or/META-INF/resources
) in the classpath or from the root of theServletContext
.默认情况下,Spring Boot 从类路径中名为 /static(或 /public或 /resources或 /META-INF/resources”)的目录或 ServletContext 的根目录提供静态内容。
在对应位置创建 index.html 文件,就可以通过 http://localhost:8080/ 直接访问欢迎页。
![](https://img-blog.csdnimg.cn/4890ebfd57ef444b9ca768848bafdbce.png#pic_center)
index 模板
在 Spring Boot Web 场景的 WelcomePageHandlerMapping 类中,有相关源码:
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {
// 使用配置在静态内容位置中的 index.html
if (welcomePage != null && "/**".equals(staticPathPattern)) {
logger.info("Adding welcome page: " + welcomePage);
setRootViewName("forward:index.html");
}
// 使用 index 模板
else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
logger.info("Adding welcome page template: index");
setRootViewName("index");
}
}
可以看出这里对应了使用欢迎页功能的两种方法。那么如何配置使用 index 模板呢?
@RequestMapping("/")
public String forwordIndex()
{
return "forward:/index.html"; // 请求转发,再由下面的控制器方法处理
}
@RequestMapping("/index.html")
public String index()
{
return "index"; // 返回视图名称,由 Thymeleaf 视图解析器解析
}
在控制器类中增加如上图所示的代码,就能以 index 模板的方式使用欢迎页功能。