java - 如果请求映射方法返回列表,Spring Boot如何解析 View 名称?

标签 java spring spring-mvc spring-boot

我正在学习 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/

相关文章:

java - @Around 在 Spring AOP 中没有被调用

java - Spring Security - 终端双重身份验证 : X. 509,用户登录表单

javascript - 特定行号错误 - Android Studio

java - 将现有的 Java 代码与 React Native 结合使用

Java isLetterOrDigit()方法、isDigit()、isLetter()

java - 如何让 Spring RabbitMQ 创建一个新队列?

javascript - 在 Spring MVC 中返回 @Async 方法结果并将其返回给 Ajax 客户端

java - Maven 构建 View 和 XML 文件丢失

spring-mvc - Spring 3.2 @ControllerAdvice无法正常工作

java - 在 Spring 中读取 2 个具有相同变量名的属性文件