Struts 2 Iterator Tag Example
In Stuts 2 the iterator tag is used to loop over a collection of objects. The iterator tag can iterate over any Collection, Map, Enumeration, Iterator, or array.
01.<table class="songTable">
02. <tr class="even">
03. <td><b>Title</b></td>
04. <td><b>Genre</b></td>
05. </tr>
06. <s:iterator value="songs" status="songStatus">
07. <tr
08. class="<s:if test="#songStatus.odd == true ">odd</s:if><s:else>even</s:else>">
09. <td><s:property value="title" /></td>
10. <td><s:property value="genre" /></td>
11. </tr>
12. </s:iterator>
13.</table>
We use the iterator tag to iterator over the collection of songs. Here the Song property is of type ArrayList. To know more about the iterator status we can create an instance of the IteratorStatus object by specifying a value to the status attribute of the iterator tag. The newly created instance will be placed in the ActionContext which can be refered using the the following OGNL expression #statusName.
The table show the different properties of the IteratorStatus object.
Name Return Type Description
index int zero-based index value.
count int index + 1
first boolean returns true if it is the first element
last boolean returns true if it is the last element
even boolean returns true if the count is an even number.
odd boolean returns true if the count is an odd number.
modulus int takes an int value and returns the modulus of count.
In Stuts 2 the iterator tag is used to loop over a collection of objects. The iterator tag can iterate over any Collection, Map, Enumeration, Iterator, or array.
01.<table class="songTable">
02. <tr class="even">
03. <td><b>Title</b></td>
04. <td><b>Genre</b></td>
05. </tr>
06. <s:iterator value="songs" status="songStatus">
07. <tr
08. class="<s:if test="#songStatus.odd == true ">odd</s:if><s:else>even</s:else>">
09. <td><s:property value="title" /></td>
10. <td><s:property value="genre" /></td>
11. </tr>
12. </s:iterator>
13.</table>
We use the iterator tag to iterator over the collection of songs. Here the Song property is of type ArrayList. To know more about the iterator status we can create an instance of the IteratorStatus object by specifying a value to the status attribute of the iterator tag. The newly created instance will be placed in the ActionContext which can be refered using the the following OGNL expression #statusName.
The table show the different properties of the IteratorStatus object.
Name Return Type Description
index int zero-based index value.
count int index + 1
first boolean returns true if it is the first element
last boolean returns true if it is the last element
even boolean returns true if the count is an even number.
odd boolean returns true if the count is an odd number.
modulus int takes an int value and returns the modulus of count.