springboot 自定義404、500錯誤提示頁面的實現(xiàn)
springboot 默認的異常處理機制
springboot
默認已經(jīng)提供了一套處理異常的機制。一旦程序中出現(xiàn)了異常 springboot
會向 /error
的 url
發(fā)送請求。在 springboot
中提供了一個名為 BasicErrorController
的類來處理 /error
請求,然后跳轉到默認顯示異常的頁面來展示異常信息
使用模板引擎
在使用 thymeleaf
等模板引擎時,springboot
會自動到 src/main/resources/templates/error/
,文件夾下尋找 404.html、500.html
的錯誤提示頁面
錯誤提示頁面的命名規(guī)則就是:錯誤碼.html
,如 404
是 404.html
,500
是 500.html
使用示例
創(chuàng)建 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
會到靜態(tài)資源文件夾尋找 404.htm、500.html
的錯誤提示頁面,命名同上。springboot
中默認的靜態(tài)資源路徑有 4
個,分別是
classpath:/METAINF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
優(yōu)先級順序為:META-INF/resources > resources > static > public
,以上 4
種路徑創(chuàng)建 error
文件夾,再創(chuàng)建 404、500
錯誤提示頁面如下
不用寫額外的映射器,就能直接請求到
到此這篇關于springboot 自定義404、500錯誤提示頁面的實現(xiàn)的文章就介紹到這了,更多相關springboot 自定義錯誤頁面內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringApplicationRunListener監(jiān)聽器源碼詳解
這篇文章主要介紹了SpringApplicationRunListener監(jiān)聽器源碼詳解,springboot提供了兩個類SpringApplicationRunListeners、SpringApplicationRunListener(EventPublishingRunListener),spring框架還提供了一個ApplicationListener接口,需要的朋友可以參考下2023-11-11