Spring Boot Welcome Page 欢迎页功能

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 an index 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 the ServletContext.

默认情况下,Spring Boot 从类路径中名为 /static(或 /public或 /resources或 /META-INF/resources”)的目录或 ServletContext 的根目录提供静态内容。

在对应位置创建 index.html 文件,就可以通过 http://localhost:8080/ 直接访问欢迎页。

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 模板的方式使用欢迎页功能。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值