SpringBoot系列教程web篇之404、500異常頁面配置
接著前面幾篇web處理請求的博文,本文將說明,當出現異常的場景下,如404請求url不存在,,403無權,500伺服器異常時,我們可以如何處理
I. 環境搭建
首先得搭建一個web應用才有可能繼續後續的測試,藉助SpringBoot搭建一個web應用屬於比較簡單的活;
建立一個maven專案,pom檔案如下
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId >
<version>2.1.7</version>
<relativePath/> <!-- lookup parent from update -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding >
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId >
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.45</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
複製程式碼
依然是一般的流程,pom依賴搞定之後,寫一個程式入口
/**
* Created by @author yihui in 15:26 19/9/13.
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
複製程式碼
II. 異常頁面配置
在SpringBoot專案中,本身提供了一個預設的異常處理頁面,當我們希望使用自定義的404,500等頁面時,可以如何處理呢?
1. 預設異常頁面配置
在預設的情況下,要配置異常頁面非常簡單,在資源路徑下面,新建 error
目錄,在下面新增400.html
,500html
頁面即可
專案結構如上,注意這裡的例項demo是沒有使用模板引擎的,所以我們的異常頁面放在static目錄下;如果使用瞭如FreeMaker模板引擎時,可以將錯誤模板頁面放在template目錄下
接下來實際測試下是否生效,我們先定義一個可能出現伺服器500的服務
@Controller
@RequestMapping(path = "page")
public class ErrorPageRest {
@ResponseBody
@GetMapping(path = "divide")
public int divide(int sub) {
System.out.println("divide1");
return 1000 / sub;
}
}
複製程式碼
請求一個不存在的url,返回我們定義的400.html
頁面
<html>
<head>
<title>404頁面</title>
</head>
<body>
<h3>頁面不存在</h3>
</body>
</html>
複製程式碼
請求一個伺服器500異常,返回我們定義的500.html
頁面
<html>
<head>
<title>500頁面</title>
</head>
<body>
<h2 style="color: red;">伺服器出現異常!!!</h2>
</body>
</html>
複製程式碼
2. BasicErrorController
看上面的使用比較簡單,自然會有個疑問,這個異常頁面是怎麼返回的呢?
從專案啟動的日誌中,注意一下RequestMappingHandlerMapping
可以發現裡面有個/error
的路徑不是我們自己定義的,從命名上來看,這個多半就是專門用來處理異常的Controller -> BasicErrorController
, 部分程式碼如下
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
@Override
public String getErrorPath() {
return this.errorProperties.getPath();
}
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String,Object> model = Collections.unmodifiableMap(getErrorAttributes(
request,isIncludeStackTrace(request,MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request,response,status,model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error",model);
}
@RequestMapping
@ResponseBody
public ResponseEntity<Map<String,Object>> error(HttpServletRequest request) {
Map<String,Object> body = getErrorAttributes(request,MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<>(body,status);
}
}
複製程式碼
這個Controller中,一個返回網頁的介面,一個返回Json串的介面;我們前面使用的應該是第一個,那我們什麼場景下會使用到第二個呢?
- 通過制定請求頭的
Accept
,來限定我們只希望獲取json的返回即可
3. 小結
本篇內容比較簡單,歸納為兩句話如下
- 將自定義的異常頁面根據http狀態碼命名,放在
/error
目錄下 - 在異常狀況下,根據返回的http狀態碼找到對應的異常頁面返回
II. 其他
0. 專案
a. 系列博文
- 190930-SpringBoot 系列教程 web 篇之 404、500 異常頁面配置
- 190929-SpringBoot 系列教程 web 篇之重定向
- 190913-SpringBoot 系列教程 web 篇之返回文字、網頁、圖片的操作姿勢
- 190905-SpringBoot 系列教程 web 篇之中文亂碼問題解決
- 190831-SpringBoot 系列教程 web 篇之如何自定義引數解析器
- 190828-SpringBoot 系列教程 web 篇之 Post 請求引數解析姿勢彙總
- 190824-SpringBoot 系列教程 web 篇之 Get 請求引數解析姿勢彙總
- 190822-SpringBoot 系列教程 web 篇之 Beetl 環境搭建
- 190820-SpringBoot 系列教程 web 篇之 Thymeleaf 環境搭建
- 190816-SpringBoot 系列教程 web 篇之 Freemaker 環境搭建
- 190421-SpringBoot 高階篇 WEB 之 websocket 的使用說明
- 190327-Spring-RestTemplate 之 urlencode 引數解析異常全程分析
- 190317-Spring MVC 之基於 java config 無 xml 配置的 web 應用構建
- 190316-Spring MVC 之基於 xml 配置的 web 應用構建
- 190213-SpringBoot 檔案上傳異常之提示 The temporary upload location xxx is not valid
b. 專案原始碼
1. 一灰灰Blog
盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激
下面一灰灰的個人部落格,記錄所有學習和工作中的博文,歡迎大家前去逛逛
- 一灰灰Blog個人部落格 blog.hhui.top
- 一灰灰Blog-Spring專題部落格 spring.hhui.top