1

In request attribute I have list of objects (say user objects) so how can I loop through it display data on my jsp page? Can I use <c:foreach> but then how I can say that it is User object and access properties of that?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Harry Joy
  • 58,650
  • 30
  • 162
  • 207

2 Answers2

5

JSTL/EL doesn't care about the exact type. All you need to ensure is that the object in question has a getter method for the given property so that you can just specify the property name.

Imagine,

public class User {

    private Long id;
    private String name;
    private Integer age;

    // Getters/setters.
}

then you can loop over a List<User> like follows:

<table>
    <c:forEach items="${users}" var="user">
        <tr>
            <td>${user.id}</td>
            <td><c:out value="${user.name}" /></td>
            <td>${user.age}</td>
        </tr>
    </c:forEach>
</table>

That's it.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

I had an issue calling the object properties with JSTL when injecting with a tag. Adding type="java.lang.Iterable" to the incoming attribute solved the issue.

<%@ attribute name="myList" required="false" type="java.lang.Iterable"%>

So when I called it:

<myTags:tag 
    myList="${Class.list}">
</myTags:tag >