Looping example through JSTL

We have seen throughout some of our previous examples that using the iteration actions makes life a lot simpler for us in JSP-land.

The <c:forEach> action uses the items attribute to specify a collection of objects. The action then repeats its nested body content over the items. If items is null, then no iteration is performed since it is treated as an empty collection. The current item in the iteration is exported as a variable. The variable has nested scope visibility. For most Collections, this is an object in the collection.

However, if it is an array of primitive types or a Map object, the current item is handled slightly differently. If the collection is of type java.util.Map, then the current item will be of type java.util.Map.Entry. There are two properties exposed:

?  key—the key under which this item is stored in the underlying Map
?  value—the value that corresponds to this key

For example, let’s look at iteration where we are looping through a collection of books.

<table> 
  <c:forEach var="book" items="${books}" varStatus="status"> 
    <tr> <td><c:out value="${book.title}"/></td> </tr> 
  </c:forEach> 
</table> 

 

Another nice feature of the iteration actions is their ability to specify ranges for the iteration. This makes it possible to iterate through a speci?ed portion of a collection. The begin and end attributes are the indices used to determine the range. If begin is speci?ed, it must be >=0. If end is speci?ed, it must be >= begin. Following is an example of iteration using begin and end.

<table> 
  <c:forEach var="book" items="${books}" varStatus="status" begin="0" end="9"> 
    <tr> <td><c:out value="${book.title}"/></td> </tr> 
  </c:forEach> 
</table>

 

JSP-SERVLET JSTL