SpringBoot 404错误页面 Whitelabel Error Page 处理方式

开门见山,三种方式解决。
有好有坏,你感觉不好的方式,了解即可。
下面测试的 SpringBoot version:2.3.1.RELEASE

问题引入

当你访问没有处理的 requestMapping 路径时,会出现“Whitelabel Error Page”

例如当你访问下面的:http://localhost:8080/http://localhost:8080/sJKnaIsf/skdjfi
在这里插入图片描述

方式1(了解):

给没有设置的路径添加 requestMaping 路径。

如果你访问 http://localhost:8080/ 时,不想让首页显示“Whitelabel Error Page”

》》》代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.springframework.web.bind.annotation.RestController;

/**
* 页面控制器
*
* @author 陶攀峰
* @version 1.0
* @date 2021-01-08 09:37
*/
@RestController
public class PageController {

/**
* 主页,默认返回空。显示空白页。
*
* @author 陶攀峰
* @date 2021-01-08 09:41
*/
@RequestMapping("/")
public String index() {
return "";
}
}

》》》测试访问
在这里插入图片描述
此时,你只是解决了首页,其他不存在的页面,同样不能解决。(了解即可)

具体想拦截所有 404 不存在的页面,可以参考下面“方式2”。

方式2(推荐):

给内嵌的容器添加错误页面。

》》》添加配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
* Web 容器配置
*
* @author 陶攀峰
* @version 1.0
* @date 2021-01-08 10:15
*/
@Configuration
public class WebContainerConfig {

/**
* 修改内嵌容器
*
* @author 陶攀峰
* @date 2021-01-08 10:37
*/
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {

return (container -> {
//ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
//ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
//ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
//container.addErrorPages(error401Page, error404Page, error500Page);

// 所有 404 页面都去访问 "/404.html"
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/404.html"));
});
}


}

》》》添加 404 错误页面,路径“resources\static\404.html”

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>页面不存在</title>
</head>
<body>
404
</body>
</html>

》》》测试(只要是不存在的页面,都等同于访问 http://localhost:8080/404.html
在这里插入图片描述

方式3(了解):

基于拦截器实现:“可以通过的页面都放行,不可用识别的页面都拦截”

拦截器使用参考:SpringMVC 拦截器