JSTL Looping and Iteration Actions

One of the most common tasks you have to deal with in JSP is outputting a sets of data by using Java for and while loop. By doing so, you create a very unreadability JSP page with opening and closing curly brace. In addition, if something wrong happens, it is difficult to detect whether the problem is. Thankfully, JSTL provides you with two useful actions for looping and iteration: for general data and for string of tokens.

The <c:forEach> action

The <c:forEach> action is very useful. You can loop over a collection or you can iterate number of times. There are two usages of <c:forEach> action. Let’s take a look at the first one which you can use <c:forEach> for loop over a collection.

The first two attributes are mandatory. You specify a collection in items attribute and each of item in collection in the var attribute. The varStatus attribute is optional. the varStatus attribute is an instance of class which implements interface LoopTagStatus. The varStatus attribute provides a set of useful properties to work with such as begin, end, current, index, count…. Let’s take a look at an example:

In the code example above we create a list which contain three people and put that list object into the request object of the page. Then we loop over the list of people and print out their first name and last name by using <c:forEach> action.

If you want the table to have alternative row background color, you can use the varStatus to do so. Let’s take a look at the modified version of the example above.

First we declare background color for odd and even rows by using CSS class.

Then we use varStatus attribute to access the LoopTagStatus object. Based on the current row of the iteration , we determine the odd and even row. Be noted that the current row of the iteration can be accessible via count property of the LoopTagStatus object.

The other usage of the <c:forEach> action is interation in a numnber of times. Here is the syntax:

The <c:forTokens> action

The <c:forTokens> action is designed to loop over a string of tokens which are seperated by a delimiter. The syntax for the <c:forEach> action is as follows:

You define the string of tokens in the items attribute. Each token in string of token should be separated by a delimiter. This delimiter is defined in the delims attribute. The var attribute is used to access each token. The other attributes such as begin, end and step allows you to define which position in the token you want to start with and end with and step of each iteration. Let’s take a look at an example of using <c:forTokens> action to display information of a person in a table layout.