Skip to main content

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: , , ,

Comments

Anonymous said…
Wow ! Merci
Anonymous said…
Very usefull.
Jwebuser said…
Hi Andrew,

thanks for this article. ;-)
This is very helpful for me.
Anonymous said…
nice info,
thanks a lot!
Anonymous said…
I was looking for a sample implementation of "varStatus" and you gave the solution for my problem.
Thanks a ton.
Anonymous said…
nice! Solved exactly what I was looking for :)
Anonymous said…
Thx - exactly what I was looking for!
Anonymous said…
Thanks. Was very helpful. It's much appreciated
aman said…
its nice informative post,its so useful.
Anonymous said…
Very nice. Good if elaborate other methods in status with few samples
Anonymous said…
\m/\m/\m/ ... very helpful !! thanks a lot.
Anonymous said…
great saved me a lot of time
Anonymous said…
Thanks a lot. It was very helpful
Anonymous said…
Thanks man!
Anonymous said…
Thanks!
Anonymous said…
awesome, thank you
Anonymous said…
To the point. Thanks! :)
Yet Another Anonymous said…
Thanks! Still useful in 2013.
Sankar said…
Great work. very nice explanation.


sankar
java training in chennai
Anonymous said…
Thanks, most simple and best implementation I have found.
Benny Volkmann said…
Awesome. Exactly what i was looking for. Thanks a lot. :)