1.存在模板引擎
有模板引擎的情况下;将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下发生此状态码的错误就会来到这里找对应的页面;
页面的名字还可以叫做4xx.html,用于响应所有4开头的错误,5xx.html用户响应所有5开头的错误。
4xx.html:
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<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>4xx</title>
</head>
<body>
<!--时间戳-->
<p>timestamp:[[${timestamp}]]</p>
<!--状态码-->
<p>status:[[${status}]]</p>
<!--错误提示-->
<p>error:[[${error}]]</p>
<!--异常对象-->
<p>exception:[[${exception}]]</p>
<!--异常消息-->
<p>message:[[${message}]]</p>
<!--JSR303数据校验的错误-->
<p>errors:[[${errors}]]</p>
</body>
</html>
下面展示500错误:
自己写一个异常类:
package org.lzl.bootproject.exception;
public class UserNotExistException extends RuntimeException {
public UserNotExistException(){
super("用户不存在!!");
}
}
自己构建异常:
@ResponseBody
@RequestMapping("/hello")
public String hello(@RequestParam("user") String user){
if(user.equals("aaa")){
throw new UserNotExistException();
}
return "hello";
}
5xx.html可以跟4xx.html的编写一样
2.没有使用模板引擎
没有模板引擎(模板引擎找不到这个错误页面),就会自动在静态资源文件夹下找error文件夹下的4xx.html…这种页面。