Search from Struts2 Library

Monday, September 22, 2008

The iterator tag

Other than the property tag, the other most commonly used tag in Struts 2 is the iterator tag. The iterator tag allows you to loop over collections of objects easily. It’s designed to know how to loop over any Collection, Map, Enumeration, Iterator, or array. It also provides the ability to define a variable in the ActionContext, the iterator status, that lets you determine certain basic information about the current loop state, such as whether you’re looping over an odd or even row. Table below provides the attributes for the iterator tag.




We already saw the iterator tag in action when we looked at the bean tag. Now we’ll
take a closer look. The chapter 6 sample application includes an example that loops
over a set of the Users of the Struts 2 Portfolio. Here’s the markup from the result page:

<s:iterator value="users" status="itStatus">
<li>
<s:property value="#itStatus.count" />
<s:property value="portfolioName"/>
</li>
</s:iterator>

As you can see, it’s straightforward. The action object exposes a set of users and the iterator tag iterates over those users. During the body of the tag, each user is in turn placed on the top of the ValueStack, thus allowing for convenient access to the user’s properties. Note that our iterator also declares an IteratorStatus object by specifying the status attribute. Whatever name you give this attribute will be the key for retrieving the iterator status object from the ActionContext, with an OGNL expression such as #itStatus. In this example, we use the iterator status’s count property to get a sequential list of our users. The output is shown in figure below



We should probably take a minute to see what else the IteratorStatus can provide
for us.

USING ITERATORSTATUS
Sometimes it’s desirable to know status information about the iteration that’s taking place. This is where the status attribute steps in. The status attribute, when defined,provides an IteratorStatus object available in the ActionContext that can provide simple information such as the size, current index, and whether the current object is in the even or odd index in the list. The IteratorStatus object can be accessed through the name given to the status attribute. Table below summarizes the information that can be obtained from the IteratorStatus object.




As you can see, this list provides just the kind of data that can sometimes be
hard to come by when trying to produce various effects within JSP page iterations.
Happy iterating!

No comments: