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/>' : ''}

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