开发者

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?


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.


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.


You can use JSTL with Struts. It has a <c:forEach> tag in its core library that will allow you to iterate through a list or any other collection easily.


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

Check this for more such examples


Struts 1.x takes care of your inner properties like this.

< logic:iterate id="user" name="userList"> < bean:write property="${userName}"/ > < /logic:iterate>

I guess as per ur example u can have. You may not need "#list." again in the value attribute < s:iterator value="users" id="list"> < s:property value="userName" /> < / s:iterator>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜