java - 为什么我的 Thymeleaf 只显示列表的最后一行
问题描述
我想显示带有名称和预订时间的前 5 门课程。
我从我的数据库中选择了前 5 门课程,并加载到一个列表中。
这是我的代码:
while (rs.next())
{
CourseBooking cb = new CourseBooking ();
List topCourses = new ArrayList();
cb.setCoursName(rs.getString(1));
cb.setBookedTimes(rs.getString(2));
topCourses.add(cb);
model.addAttribute("topCourses ", topCourses );
}
但是当我使用“th:each”时,它只显示前 5 名的最后一行,不能
阅读整个列表。
<tr th:each="m : ${topCourses }">
<td th:text="${m.coursName}"></td>
<td th:text="${m.bookedTimes}"></td>
</tr>
解决方案
(根据评论——您需要将列表的创建移到 for 循环之外。)您的代码应如下所示:
List topCourses = new ArrayList<CourseBooking>();
while (rs.next()) {
CourseBooking cb = new CourseBooking ();
cb.setCoursName(rs.getString(1));
cb.setBookedTimes(rs.getString(2));
topCourses.add(cb);
}
model.addAttribute("topCourses ", topCourses );
推荐阅读
- sapui5 - 未生成 SAP Fiori Elements 导航链接
- java - 使用 DDL 脚本时,JPA 始终无法创建 (H2) 数据库模式和表
- reactjs - 不同的 WebSocket“onmessage”处理程序取决于屏幕
- javascript - 使用 Typescript 定位最新版本的 EcmaScript
- javascript - jQuery selector for all in a div if class includes a certain string
- python - 什么时候可以捕获错误(在函数中)?
- powerbi - 使用 DAX,我如何创建一个度量来对最近记录的列求和,以便按日期显示总计?
- math - 如何计算给定数字落在一组数字内的数字括号?
- javascript - 如何仅在客户端在 Vue.js 3 中动态导入 CKEditor?
- javascript - 初学者 javascript 按钮