當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot 配置错误页
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot 配置错误页
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
錯誤頁絕對是所有的 WEB 項目之中必須具有的一項信息顯示處理,但是在傳統的 WEB 項目開發過程之中,
錯誤頁都是在 web.xml 文件之中進行配置的,不過遺憾的是 SpringBoot 之中并不存在有 web.xml 配置
文件這一項,那么如果要想進行錯誤頁的處理,最好的做法是需要根據每一個錯誤代碼創建一個屬于自己的
錯誤顯示頁。1、 所有的錯誤頁都是普通的靜態文件,那么建議在“src/main/static”目錄下創建幾個常見的錯誤頁
(常見的錯誤的 HTTP 返回編碼:404、500、400)error_404.html<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1>對不起,出現了404錯誤!</h1></body>
</html>error_500.html<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1>對不起,出現了500錯誤!</h1></body>
</html>error_400.html<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1>對不起,出現了400錯誤!</h1></body>
</html>
2、 添加一個錯誤頁的配置類,在啟動類中編寫一個錯誤頁的配置項;package com.microboot.config;import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;@Configuration
public class ErrorPageConfig {@Beanpublic EmbeddedServletContainerCustomizer containerCustomizer() {return new EmbeddedServletContainerCustomizer() {@Overridepublic void customize(ConfigurableEmbeddedServletContainer container) {ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST,"/error_400.html");ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND,"/error_404.html");ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error_500.html");container.addErrorPages(errorPage400, errorPage404,errorPage500);}};}
}
那么此時只要出現了錯誤,就會找到相應的 http 狀態碼,而后跳轉到指定的錯誤路徑上進行顯示。
?
總結
以上是生活随笔為你收集整理的SpringBoot 配置错误页的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot 数据验证错误处理
- 下一篇: SpringBoot 全局异常处理