Spring Boot Whitelabel Error 教程展示了如何在 Spring Boot 应用中配置和显示错误消息。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
WhiteLabel 错误页面
WhiteLabel 错误页面是通用的 Spring Boot 错误页面,当不存在自定义错误页面时显示。
通过将server.error.whitelabel.enabled
设置为false
,可以在application.properties
文件中禁用 WhiteLabel 错误。
禁用 WhiteLabel 错误的另一种方法是排除ErrorMvcAutoConfiguration
。
或者,可以在注解中进行排除。
当禁用 WhiteLabel 错误页面并且未提供自定义错误页面时,将显示 Web 服务器的错误页面(Tomcat,Jetty)。
Spring Boot 自定义错误页面
如果不使用 Thymeleaf 的模板引擎,我们可以在一个src/main/resources/public/errors
目录放置一个普通的自定义错误页。
resources/public/errors/404.html
这是一个 404 错误一般错误页面。
resources/templates/error.html
可以将使用模板的通用错误页面放置在src/main/resources/templates/
目录中。
resources/templates/error/404.html
可以将使用模板的特定错误页面放在src/main/resources/templates/error/
目录中。
Spring Boot 自定义错误页面示例
在下面的示例中,我们创建一个简单的 Spring Boot 应用,其中使用针对 404 错误的自定义错误页面。
这是 Spring 应用的项目结构。
pom.xml
这是 Maven pom.xml
文件。 我们有spring-boot-starter-web
和spring-boot-starter-thymeleaf
。
resources/application.properties
在application.properties
中,我们可以使用这些设置中的 on 来关闭 WhiteLabel Error。 如果我们提供一个自定义错误页面,它将自动优先于 WhiteLabel 错误。
com/zetcode/controller/MyController.java
我们有一个简单的控制器,用于返回首页的文本消息。
resources/templates/error/404.html
这是使用 Thymeleaf 创建的自定义模板错误页面。
com/zetcode/Application.java
这段代码设置了 Spring Boot 应用。
在本教程中,我们介绍了 WhiteLabel 错误,并展示了如何创建自定义错误页面。