springboot 自定义404、500错误提示页面的实现
springboot 默认的异常处理机制
springboot 默认已经提供了一套处理异常的机制。一旦程序中出现了异常 springboot 会向 /error 的 url 发送请求。在 springboot 中提供了一个名为 BasicErrorController 的类来处理 /error 请求,然后跳转到默认显示异常的页面来展示异常信息
使用模板引擎
在使用 thymeleaf 等模板引擎时,springboot 会自动到 src/main/resources/templates/error/,文件夹下寻找 404.html、500.html 的错误提示页面
错误提示页面的命名规则就是:错误码.html,如 404 是 404.html,500 是 500.html
使用示例
创建 springboot 项目如下
404、500 错误提示页面结构如下

application.properties 项目配置文件
server.port=8080 #它的默认值就是classpath:/templates/,源码在ThymeleafProperties类中 spring.mvc.view.prefix=classpath:/templates/ #它的默认值就是.html,源码在ThymeleafProperties类中 spring.mvc.view.suffix=.html spring.thymeleaf.cache=false
404 页面内容如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>404</title>
<link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow" rel="external nofollow" />
<link rel="stylesheet" type="text/css" th:href="@{/css/404.css}" rel="external nofollow" />
</head>
<body>
<div id="banner" style="height: 600px;width: 600px;margin-left: 370px"></div>
</body>
</html>
500 页面内容如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>500</title>
<link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow" rel="external nofollow" />
<link rel="stylesheet" type="text/css" th:href="@{/css/500.css}" rel="external nofollow" />
</head>
<body>
<div id="banner" style="height: 600px;width: 600px;margin-left: 370px"></div>
</body>
</html>
controller 如下
@Controller
public class PageController {
// 跳转到登录页
@GetMapping(path = "/toLogin")
public String toLogin() {
int code = 1/0;
return "login";
}
}
404.html 页面测试
访问不存在的接口:http://localhost:8080/aaaa,结果如下

500.html 页面测试
访问已存在的接口:http://localhost:8080/toLogin,结果如下

没有使用模板引擎
如果没有使用 thymeleaf 等模板引擎时,springboot 会到静态资源文件夹寻找 404.htm、500.html的错误提示页面,命名同上。springboot 中默认的静态资源路径有 4 个,分别是
classpath:/METAINF/resources/classpath:/resources/classpath:/static/classpath:/public/
优先级顺序为:META-INF/resources > resources > static > public,以上 4 种路径创建 error 文件夹,再创建 404、500 错误提示页面如下

不用写额外的映射器,就能直接请求到
到此这篇关于springboot 自定义404、500错误提示页面的实现的文章就介绍到这了,更多相关springboot 自定义错误页面内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot(cloud)自动装配bean找不到类型的问题
这篇文章主要介绍了SpringBoot(cloud)自动装配bean找不到类型的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-02-02
IDEA中Maven依赖包无法下载或导入的解决方案(系统缺失文件导致)
在配置Maven环境时,可能会遇到各种报错问题,首先确保Maven路径配置正确,例如使用apache-maven-3.5.0版本,则需要在系统环境变量的Path中添加其bin目录路径,并上移优先级,接下来,在Maven的conf目录下修改settings.xml文件,将镜像源改为阿里云2024-09-09
mybatis-plus 关于savebatch,saveorupdatebatch遇到的坑及解决办法
本文主要介绍了mybatis-plus 关于savebatch,saveorupdatebatch遇到的坑及解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-01-01


最新评论