1、要在Spring Boot項目中配置自定義的錯誤頁面,你可以遵循以下步驟:
1.1、pom.xml引入thymeleaf
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
1.2、創建thymeleaf模版引擎的自定義錯誤頁面
1、HTML 代碼中的 是一個名字空間聲明,用于啟用 Thymeleaf 的屬性。
2、Thymeleaf 是一個 Java 庫,可以用于在網頁上顯示應用程序產生的數據或文本
3、在你的項目資源文件夾(通常是src/main/resources)中創建一個文件夾,命名為templates。
4、在templates文件夾中創建你想要的錯誤頁面,例如error.html、404.html或500.html
我的html放置在src/main/resources/templates/error下
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>訪問錯誤</title><style>body {background-color: #F2F2F2;font-family: Arial, sans-serif;}.error-container {text-align: center;margin-top: 50px;}.error-container h1 {font-size: 36px;color: #333;}.error-container p {font-size: 18px;color: #666;}</style>
</head>
<body><div class="error-container"><h1>抱歉,頁面未找到!</h1><p>您訪問的頁面不存在或已被刪除,請檢查URL以及請求是否正確。</p></div>
</body>
</html>
1.3、創建一個自定義錯誤處理類
創建一個自定義的錯誤處理類,實現ErrorController接口。該類將處理所有錯誤請求,并將請求重定向到你自定義的錯誤頁面。
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;@RestController
public class CustomErrorController implements ErrorController {private static final String PATH = "/error";@RequestMapping(value = PATH, method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)public ModelAndView handleError(HttpServletRequest request) {Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");ModelAndView mav = new ModelAndView();if(statusCode == HttpStatus.NOT_FOUND.value()){//在src/main/resources/templates/error下尋找404.html頁面mav.setViewName("error/404");}else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()){//在src/main/resources/templates/error下尋找500.html頁面mav.setViewName("error/500");}else if(statusCode == HttpStatus.FORBIDDEN.value()){//在src/main/resources/templates/error下尋找403.html頁面mav.setViewName("error/403");}else{//默認錯誤頁面mav.setViewName("error/error");}return mav;}@Overridepublic String getErrorPath() {return PATH;}
}
1.4、配置錯誤頁面
在application.properties或application.yml配置文件中,添加以下配置:
1.4.1、application.properties配置
server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
##我的文件存放在/templates/error下
server.error.path=/error
1.4.2、application.yml配置
server:error:whitelabel:enabled: falsepath: /errorspring:mvc:throw-exception-if-no-handler-found: trueresources:add-mappings: false