3.5. Using Indexed Properties in a JSTL Loop
Problem
You want to use indexed bean properties with the Struts
html tags in a JSTL c:forEach
loop instead of Struts
logic:iterate
loop.
Solution
To create fields for a simple
indexed property, use the bean:define tag to
expose the loop counter as a scripting variable that can be used in a
runtime expression:
<c:forEach var="theItem" items="${MyForm.myItems}" varStatus="loopStatus">
<bean:define id="itemIndex">
<c:out value="${loopStatus.index}"/>
</bean:define>
<br/><html:text property='<%="myItem["+itemIndex+"]"%>'/>
</c:forEach>If the indexed property is a nested bean and you are using the
indexed="true" property, then replace the Struts
logic:iterate tag with the JSTL
c:forEach:
<c:forEach var="theNestedItem" items="${MyForm.myNestedItems}">
<br/><html:text name="theNestedItem"
property="nestedProperty"
indexed="true"/>
</c:forEach>Discussion
The
c:forEach tag
provided by JSTL provides additional functionality and can be easier
to use than the logic:iterate tag. The items to
loop through can be specified using EL. The JSTL tag permits greater
control for looping over a subset of the collection, and details on
the loop status are easily obtained. However, as is common to all
JSTL tags, no scripting
variables are created. As was shown in other recipes in this chapter,
runtime expressions may have to be used when dealing with indexed
properties. This is particularly true if you are not using the
struts-el tag libraries.
The
bean:define ...