user3235376
user3235376

Reputation: 87

JSP table from ArrayList creation

I need to show some data inside a table (jsp). The data are being passed like this:

request.setAttribute("name", nameVariable);
request.setAttribute("surname", surnameVariable);
request.setAttribute("list", list); //Here are stored ultimately all the data (so name and surname also)

My list is being updated and I need to have the list being updated also. I know my list gets more items, but this code prints only last record from that list. What should I change in my code to be able to print all records from list in table?

My jsp:

<c:forEach items="${list}">
        <tr>
            <td>${name}</td>
            <td>${surname}</td>
        </tr>
    </c:forEach>

Upvotes: 0

Views: 1342

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

You're always printing the same request attributes, at each iteration of the loop, completely ignoring the current element of the list. Assuming the list contains objects of type Person (for example), which has a getName() and a getSurname() method, the code should be

<c:forEach items="${list}" var="person">
    <tr>
        <td>${person.name}</td>
        <td>${person.surname}</td>
    </tr>
</c:forEach>

Just like, in Java, a foreach loop would define a person variable for the current person during the itertion:

for (Person person: list) {
    System.out.println(person.getName());
    System.out.println(person.getSurname());
}

Upvotes: 3

Related Questions