Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

EL List traversing

 
Vivek Kinra
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On a JSP page, How can I traverse a List of Objects say of class A and pull the values of there instance variables...

e.g

class A{
private String name;

// getter and setter's for name...

}
Thanks...
 
Shivani Chandna
Ranch Hand
Posts: 380
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use JSTL c:forEach tag to iterate over the List.

<c:forEach items="listOfObjects" var="currObject>
${listOfObjects.name}
${listOfObjects.secondProperty}
${listOfObjects.otherProperty}
</c:forEach>

OR
If you want access for a given index only then ::
${listOfObjects[0].name}
${listOfObjects[0].secondProperty}
${listOfObjects[0].otherProperty}

Regards,
Shivani
 
Vivek Kinra
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Shivani... Your second option will not work because the return type from List is Object and then we have to cast that object to its class to access the "name" property.

I haven't tried second one but I think it will have the casting problem too..

Thanks...
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Shivani... Your second option will not work because the return type from List is Object and then we have to cast that object to its class to access the "name" property

Actually no, you don't have to. EL will do that for you. If you've put Person objects in a List, you don't have to cast to Person when getting the value back.
 
salil verma
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vivek, you can see the same by executing the following code

 
Vivek Kinra
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Salil, Satou....

It work's great...My mistake was I was trying to traverse the list by directly using the List instead of setting it in request like


<c:forEach var="object_name" items='${a}'>
<br>
<c ut value='${object_name.name}'>
</c ut>
</c:forEach>

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic