- 定义错误页面
- 使用HTTP状态码
- 在Controller中处理异常
- 全局统一异常处理
在用户访问页面时,常常会出现页面无法访问、访问路径错误等一系列问题,我们需要根据错误异常类型给用户相应的提示。
第一种最简单的方法:定义错误页面
在出现错误时,springboot会跳转到自己的错误页面。
我们可以自己定义错误页面,在templates目录下新建error目录——》在error下新建404.HTML、403.HTML与500.HTML。springboot会自动在项目中寻找404,403等以错误编号命名的页面,并在发生错误时跳转。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>login</title>
<link rel="stylesheet" href="../static/css/bootstrap.css" type="text/css" >
</head>
<body>
`<div class="container" style="max-width: 600px;margin-top: 100px;">
<div class="jumbotron">
<h2>404</h2>
<p>对不起,你访问的页面不存在</p>
</div>
</div>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js" ></script