The c:forEach tag in the core JSTL library is one of the most useful and versatile being used whenever it is necessary to iterate over data. A common use of c:forEach is to produce a HTML table containing data gathered from a SQL query or other data source. The example below shows a simple usage of the c:forEach tag which acquires it's data from a bean called people wraps a collection of person objects. The forEach iterates over the people producing one row for each person. Each person has a name, age and height properties.

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp=
"http://java.sun.com/JSP/Page"
 
xmlns:c="http://java.sun.com/jsp/jstl/core"
 
version="2.0">
<html xmlns=
"http://www.w3.org/1999/xhtml">
  <head>
    <title>c:forEach Example</title>
  </head>
  <body>
    <table>
      <c:forEach var=
"person" items="${people.people}">
        <tr>
          <td>$
{person.name}</td>
          <td>$
{person.age}</td>
          <td>$
{person.height}</td>
        </tr>
      </c:forEach>
    </table>
  </body>
</html>

While this is certainly a nice working example it is possible to produce better results but introducing another tag c:choose. By using c:choose one can apply banding to the table which makes it easier to view the page. To apply a different colour to alternate rows a construct such as that shown below can be used.

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp=
"http://java.sun.com/JSP/Page"
 
xmlns:c="http://java.sun.com/jsp/jstl/core"
 
version="2.0">
<html xmlns=
"http://www.w3.org/1999/xhtml">
  <head>
    <title>c:forEach Example</title>
  </head>
  <body>
    <table>
      <c:forEach var=
"person" items="${people.people}" varStatus="rowCounter">
        <c:choose>
          <c:when test=
"${rowCounter.count % 2 == 0}">
            <c:set var=
"rowStyle" scope="page" value="odd"/>
          </c:when>
          <c:otherwise>
            <c:set var=
"rowStyle" scope="page" value="even"/>
          </c:otherwise>
        </c:choose>
        <tr
class="${rowStyle}">
          <td>$
{person.name}</td>
          <td>$
{person.age}</td>
          <td>$
{person.height}</td>
        </tr>
      </c:forEach>
    </table>
  </body>
</html>