JSTL forEach varStatus index example

JSTL forEach loop provides varStatus attribute that helps to keep the track of current iteration. It is essential to have an index of current iteration while working with loop. 

VarStatus attribute of JSTL forEach tag provides the capability to get an index of current iteration. Developer can get that index by invoking index method on varStatus object. The returned index is zero based. It means the first iteration will have index 0. If there are 10 iterations, the last iteration will have index 9. This is same like index of any other data structure in JAVA like array, ArrayList, LinkedList, HashSet, etc.

JSTL forEach tag varStatus attribute Example:

Assume that the code below iterates over the list of 3 products that contains following names in order:

Red Pen, Green Pen, Pink Pen

 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                            "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL forEach varStatus index Example</title>
</head>
<body>
  <c:forEach items="${productList}" var="product" varStatus="status">
     <c:out value="${status.index}"/>.<c:out value="${product.name}" escapeXml="false" />
  </c:forEach>
</body>
</html>

Output:

0. Red Pen

1. Green Pen

2. Pink Pen


As you can see above, we printed name of the products with its index in the list. This index is printed using varStatus attribute of JSTL forEach tag. varStatus attribute specifies the object name. In the example above we specified it as a "status". Using this object, we invoked index method by calling it this way: status.index

index method returns an interger value that represents the index of current iteration. Since index is zero based, it started with 0 in first product. However, you may want to start with 1 when displaying it on the browser. In that case, you can use ${status.index + 1} in value attribute of JSTL c out tag.