Shayimerdan
Shayimerdan

Reputation: 67

Why my Thymeleaf showing only the last line of the List

I want to show the top 5 courses with name and booked times.

I have choosed top 5 courses from my Database , and loaded in one List.

Here is my code:

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

But when im using "th:each",it is showing only the last line of top 5,and cannot

read the whole List.

            <tr th:each="m : ${topCourses }">      
                <td th:text="${m.coursName}"></td>  
                <td th:text="${m.bookedTimes}"></td>
            </tr>

Upvotes: 0

Views: 271

Answers (1)

Metroids
Metroids

Reputation: 20477

(Per the comment -- you need to move the creation of your list outside the for loop.) Your code should look like this:

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 );

Upvotes: 1

Related Questions