Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you iterate through a list of objects?

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?

like image 688
Kevin Avatar asked May 02 '10 20:05

Kevin


2 Answers

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.

like image 122
leonbloy Avatar answered Oct 10 '22 08:10

leonbloy


You can do like this

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

Observe that no need of #list there.

The other way is

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

insetead of id give it as var.Since we don’t specify a scope for var, this new user reference exists in the default “action” scope—the ActionContext. As you can see, we then reference it with the # operator.

like image 24
pavan Avatar answered Oct 10 '22 09:10

pavan