首页 > 解决方案 > spring boot 不会在页面上显示对象列表

问题描述

我有一个使用 SpringBoot 构建的简单 Web 应用程序,但在页面上显示对象列表时遇到问题:

这是我的模型:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public class Slot {
    private Long id;
    private DateTime startTime;
    private DateTime finishTime;
    private String title;
    private String description;
}

控制器:

@RestController
public class AdminController {
    @GetMapping("/admin/slots")
    public ModelAndView getSlots() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("admin/slots");

        List<Slot> slots = .. get slots from other service ..
        modelAndView.addObject("slots", slots);
        return modelAndView;
    }
}

看法:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Slot List</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <table class="table" id="slot-table">
        <thead>
        <tr>
            <th>id</th>
            <th>start time</th>
            <th>finish time</th>
            <th>title</th>
            <th>description</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="slot : ${slots}">
            <td th:text="${slot.getId()}"></td>
            <td th:text="${slot.getStartTime()}"></td>
            <td th:text="${slot.getFinishTime()}"></td>
            <td th:text="${slot.getTitle()}"></td>
            <td th:text="${slot.getDescription()}"></td>
        </tr>
        </tbody>
    </table>
</body>
</html>

当我在浏览器中打开时,我可以看到表格标题但看不到表格中的数据,我做错了什么吗?

标签: spring-mvcspring-boot

解决方案


要访问视图页面中的字段,您不必使用 getter 和 setter。只需使用点运算符访问,如下所示。

${slot.id}
${slot.startTime}
${slot.finishTime}
${slot.title}
${slot.description}

推荐阅读