JSTL 'forEach' looping tricks using varStatus
Do you have a JSTL forEach loop in your JSP page displaying a list of results? Have you ever wanted to do something different for each row, or maybe do something for all but the last row?
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.
The code example below will display a horizontal rule under each item apart from the very last one:
<c:forEach var="thing" items="${things}" varStatus="status">
<a href="${thing.link}">${thing.description}</a>
${not status.last ? '<hr/>' : ''}
</c:forEach>The important bits of the above snippet are the varStatus="status" and status.last. The first one defines a 'status' variable, and the second one accesses it to ask if this row is the 'last'.The status object has a number of useful methods:
current, index, count, first, last, begin, step, end
Technorati Tags: forEach, JSTL, JSP, Andrew Beacock


Buy Stuff From Amazon 
14 Comments:
Wow ! Merci
Very usefull.
Hi Andrew,
thanks for this article. ;-)
This is very helpful for me.
nice info,
thanks a lot!
I was looking for a sample implementation of "varStatus" and you gave the solution for my problem.
Thanks a ton.
nice! Solved exactly what I was looking for :)
Thx - exactly what I was looking for!
Thanks. Was very helpful. It's much appreciated
its nice informative post,its so useful.
Very nice. Good if elaborate other methods in status with few samples
\m/\m/\m/ ... very helpful !! thanks a lot.
great saved me a lot of time
Thanks a lot. It was very helpful
Thanks man!
Post a Comment