Spring Boot 自定义错误(404.html)页面
使用SpringBoot的自动配置原理进行异常处理
SpringBoot自动配置了一个类ErrorMvcAutoConfiguration
来处理处理异常,有兴趣的可以去看一下,然后在这个类中定义一个错误的BasicErrorController类,主要代码有如下:
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
/**
* 错误的页面响应
*/
@RequestMapping(produces = {"text/html"})
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
// 得到一个modelAndView对象
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}
/**
* 错误的json响应
*/
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = this.getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity(status);
} else {
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity(body, status);
}
}
}
多的代码就不深究了,感兴趣的可以去看一下。上边的代码也就是说,针对不同的请求方式,会返回不同的结果,其关键在于@RequestMapping
注解的produces = {"text/html"}
属性上
Spring Boot 官网介绍
如果要显示给定状态代码的自定义 HTML 错误页面,可以将/error/4xx.html
文件添加任意Spring boot 资源文件目录中。错误页面可以是静态 HTML (即添加到任何静态资源目录下) ,也可以通过使用模板构建(将html放置在templates/error/
目录下)。文件的名称应该是确切的状态代码或一系列掩码。
也就是说不止有404,所有能够确切触发的状态码都可以拥有对应的xxx.html
使用
例如:将404映射到一个静态 HTML 文件,则目录为
普通静态HTML
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>
模板
使用模板的好处就是可以通过 thymeleaf
获取 请求域的值
使用模板时的目录也就是将 \error 文件夹放入 resources
下的 templates
文件夹:
src/
+- main/
+- java/
| + <source code>
+- resources/
+- templates/
+- error/
| +- 404.html
+- <other public assets>
演示 404 html 在两种情况下的显示
404.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul>
<!-- 这里使用的是thymeleaf -->
<li>错误状态码:[[${status}]]</li>
<li>错误消息:[[${error}]]</li>
<li>异常路径:[[${path}]]</li>
<li>异常消息:[[${message}]]</li>
<li>当前时间:[[${timestamp}]]</li>
</ul>
</body>
</html>
第一种情况 当 error
文件夹放在 spring boot 普通静态资源目录下时
使用浏览器触发 404 异常后,浏览器显示该效果
第二种情况 当 error
文件夹放在 spring boot templates
目录时
使用浏览器触发 404 异常后,浏览器显示该效果
注意
:error文件夹同时处于普通静态资源目录和templates
时,tempalates
优先级高。
更多推荐
Spring Boot 自定义错误(404.html)页面
发布评论