我正在学习 Spring Boot 应用程序中的 View 分辨率。为了进行实验,我在 Spring Boot 应用程序中创建了一个 Controller ,如下所示
@Controller
@RequestMapping("/rooms")
public class RoomController {
private static List<Room> roomList = new ArrayList<>();
static {
for (int i = 1; i <= 10; i++) {
roomList.add(new Room("Room " + i, "Name " + i, "Q"));
}
}
@GetMapping
public List<Room> getRooms(Model model) {
model.addAttribute("rooms", roomList);
// View name is rooms.html
// Returning a room list object with a different name
// Also, no other custom view resolvers are registered
return roomList;
}
}
另外,这是我的 rooms.html 文件
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Hotel | Rooms</title>
<link th:href="@{/css/style.css}" rel="stylesheet" />
</head>
<body>
<table border="1">
<tr>
<th>Room Number</th>
<th>Name</th>
<th>Bed Info</th>
</tr>
<tr th:each="room:${rooms}">
<td th:text="${room.number}"></td>
<td th:text="${room.name}"></td>
<td th:text="${room.bedInfo}"></td>
</tr>
</table>
</body>
</html>
当我运行应用程序并点击https://localhost:8000/rooms时,我仍然看到正确的 View rooms.html 正在渲染。
根据我的理解,它不应该能够解析 View “rooms.html”,因为我没有返回 View 名称字符串或 Model 或 ModelAndView 对象。
这是预期的行为还是我错过了什么?
最佳答案
Spring 足够聪明,可以从 URI 中找出 View 的名称。
有一个类DefaultRequestToViewNameTranslator
哪个可以完成这项工作。它知道如何构造 View 名称,使用什么前缀、后缀。
RequestToViewNameTranslator
that simply transforms the URI of the incoming request into a view name. [...]The default transformation simply strips leading and trailing slashes as well as the file extension of the URI, and returns the result as the view name with the configured prefix and a suffix added as appropriate.
The documentation of DefaultRequestToViewNameTranslator
关于java - 如果请求映射方法返回列表,Spring Boot如何解析 View 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52892231/