How do you iterate through a list of objects?

Kevin picture Kevin · May 2, 2010 · Viewed 58.7k times · Source

I have a User class that has a String username in it. I have a list of users that I'm trying to display in a table using

                         <s:iterator value="users" id="list">
                                <tr>
                                    <td><s:property value="#list.username" /></td>
                                    <td></td>
                                    <td></td>
                                    <td></td>
                                </tr>
                         </s:iterator>

The rows are being displayed the right number of times, so it's iterating through my list properly. However, I don't know how to access the username property to display it. Obviously what I have above isn't correct... Any ideas?

Answer

leonbloy picture leonbloy · May 2, 2010

First, in Struts2 2.1.x the id attribute is deprecated, var should be used instead (ref)

I think the # is misused there. Besides, "list" seems a bad name for what is to be assigned in each iteration... I think "user" is more appropiate.

IIRC, the syntax is

 <s:iterator value="users" var="user">
  ...  <s:property value="#user.username" />
 </s:iterator>

Further, you don't need to assign the current item in the iterator for such a simple case. THis should also work:

 <s:iterator value="users">
  ...  <s:property value="username" />
 </s:iterator>

Also you might want to try this:

  <s:iterator value="users">
      ...  <s:property />      <!-- this outputs the full object, may be useful for debugging -->
  </s:iterator>

UPDATE: I corrected the bit about the #, it was ok.