1. 簡介
在本教程中,我們將探討如何在 Spring MVC 應用程序中獲取和解決 Circular View Path 錯誤。
2. 依賴項
為了演示這一點,我們創建一個簡單的 Spring Boot Web 項目。首先,我們需要在 Maven 項目文件中添加 Spring Boot Web Starter 依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>3. 還原問題
然後,讓我們創建一個簡單的 Spring Boot 應用程序,其中包含一個 Controller,該 Controller 映射到一個路徑:
@Controller
public class CircularViewPathController {
@GetMapping("/path")
public String path() {
return "path";
}
}返回值是用於產生響應數據的視圖名稱。在本例中,返回值是 path,它與 path.html模板相關聯:
<html>
<head>
<title>path.html</title>
</head>
<body>
<p>path.html</p>
</body>
</html>在啓動服務器後,我們可以通過向 http://localhost:8080/path 發送 GET 請求來重現該錯誤。 結果將是循環視圖路徑錯誤:
{"timestamp":"2020-05-22T11:47:42.173+0000","status":500,"error":"Internal Server Error",
"message":"Circular view path [path]: would dispatch back to the current handler URL [/path]
again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view,
due to default view name generation.)","path":"/path"}
4. 解決方案
默認情況下,Spring MVC 框架將 InternalResourceView 類作為視圖解析器。因此,如果 @GetMapping 的值與視圖相同,則會引發 Circular View path 錯誤。
一種可能的解決方案是重命名視圖並更改控制器方法中的返回值。
@Controller
public class CircularViewPathController {
@GetMapping("/path")
public String path() {
return "path2";
}
}如果我們不想重命名視圖並更改控制器方法的返回值,那麼另一種解決方案是選擇另一個視圖處理器。
對於最常見的用例,我們可以選擇 Thymeleaf Java 模板引擎。 讓我們將 spring-boot-starter-thymeleaf 依賴添加到項目中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>在重建項目後,我們可以再次運行它,並且請求成功。在這種情況下,Thymeleaf 會替換 InternalResourceView 類。
5. 結論
在本教程中,我們探討了圓形視圖路徑錯誤,分析了其原因,並學習瞭如何解決該問題。