简体   繁体   中英

How does spring boot resolve view names if the request mapping method returns a list?

I am learning view resolution in spring boot applications. For experimenting, I have created a controller in a spring boot application as below

@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;
    }
}

Also, this is my rooms.html file

<!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>

When I run the application, and hit https://localhost:8000/rooms , I still see the correct view rooms.html getting rendered.

From my understanding, it should not have been able to resolve to the view "rooms.html", since I am not returning a view name string or a Model or ModelAndView objects.

Is this an expected behaviour or am I missing something?

Spring is smart enough to figure out the name of a view from a URI.

There is a class DefaultRequestToViewNameTranslator which does the job. It knows how to construct a view name, what prefix, suffix to use.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM