I have two items from my model and I want to iterate them at the same using jstl foreach. how can I achieve this using a correct syntax?
Iterating over array using JSTL forEach loop For iterating over an array e.g. String array or integer array in JSP page, "items" attribute must resolved to an array. You can use expression language to get an Array stored in of scope available in JSP e.g. page scope, request scope, session or application scope.
varStatus is what you want! You declare a new variable within the main forEach JSP block which will allow you to access the internal loop counter of the for-each loop. Then you can call a number of methods on that object to be able to do conditional processing.
These tag used as a good alternative for embedding a Java while, do-while, or for loop via a scriptlet. The < c:for each > tag is most commonly used tag because it iterates over a collection of object.
You can call varStatus.index
to get the index of the current round of iteration, and then use it as a lookup for the second list.
For example, if you have two lists people.firstnames
and people.lastnames
you can do:
<c:forEach var="p" items="${people.firstnames}" varStatus="status">
<tr>
<td>${p}</td>
<td>${people.lastnames[status.index]}</td>
</tr>
</c:forEach>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With