首页 > 解决方案 > 为什么我的 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>

标签: javaspring-bootwebthymeleaf

解决方案


(根据评论——您需要将列表的创建移到 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 );

推荐阅读