Freud's Blog

Stay hungry, stay foolish. 少年辛苦终身事,莫向光阴惰寸功。

Spring Boot(十三) - 自定义WhiteLabel错误页面

Posted on By Freud Kang

自定义whitelabel错误页面

当使用浏览器浏览访问遇到服务器端错误的时候,Spring Boot 默认会配置一个whitelabel错误页面。

关闭whitelabel

可以通过使用server.error.whitelabel.enabled=false来关闭默认的错误页面,以使用servlet容器的默认页面。

覆盖whitelabel

覆盖whitelabel错误页面的方法,取决于你选用了什么页面模版。

  • ThymeLeaf:在template中新建一个error.html文件
  • FreeMarker:添加一个error.ftl模版
  • 定义一个名为error的Bean ErrorMvcAutoConfiguration.java

指定HTTP错误类型

如下可以制定当出现404显示404.html页面,如果出现5**的错误,则显示5xx.html

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- public/
             +- error/
             |   +- 404.html
             |   +- 5xx.html
             +- <other public assets>

实验

本实验基于Thymeleaf进行

创建一个Maven项目

/images/blog/spring-boot/13-white-label-page/01-new-maven-project.png

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.freud.test</groupId>
	<artifactId>spring-boot-13</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-boot-13</name>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
		<relativePath />
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

application.yml

spring:
  application:
    name: test-13
    
server: 
#  此处如果取消掉server.error.whitelabel.enabled的注释则默认的whitelabel就会失效
#  error:
#    whitelabel:
#      enabled: false
  port: 9090

error.html

<!DOCTYPE html>
<html>
	<head>
		<title>My Own Error Page!</title>
	</head>
	<body>
		This is the error page from freud's define
	</body>
</html>

App.java

package com.freud.test.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Freud
 */
@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

项目结构

/images/blog/spring-boot/13-white-label-page/02-project-hierarchy.png

运行结果

/images/blog/spring-boot/13-white-label-page/03-explorer-run-result.png

参考资料

Spring Boot Reference Guide : http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/

《JavaEE开发的颠覆者 Spring Boot实战》 - 汪云飞