This post helps you understand and use the <c:forEach> tag in the JSTL core tags library.

You know, <c:forEach> is the looping construct in the JSTL. We use <c:forEach> to iterate over a collection of objects and display their values. The objects can be POJOs or plain data type values.

 

JSTL <c:forEach> Syntax

<c:forEach

    items="<object>"

    begin="<int>"

    end="<int>"

    step="<int>"

    var="<string>"

    varStatus="<string>">


    ...


</c:forEach>

 

Attributes:

Name

Required

Type

Description

items

False

java.lang.Object

Collection of items to iterate in the loop.

begin

False

int

Begin index of the iteration. Iteration begins at the value mentioned in this attribute value. (if items specified) First item has index of 0.

end

False

int

End index of the iteration. Iteration stops at the value mentioned in this attribute value (inclusive). (if items specified) .

step

False

int

Iteration processes for the step value mentioned in this attribute.

var

False

java.lang.String

Name of the scoped variable which holds the current item in the iteration. This variable’s type depends on the items in the iteration and has nested visibility.

varStatus

False

java.lang.String

Name of the scoped variable which holds the loop status of the current iteration. This variable is of type javax.servlet.jsp.jstl.core.LoopTagStatus and has nested visibility.

 

JSTL <c:forEach> Example:

The following JSP example iterates over the choices user selected and displays them.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>&lt;c:forEach&gt; Demo</title>
    </head>
    <body>
      <h1>&lt;c:forEach&gt; Demo</h1>
      <form name="forEachForm" 
          action="${pageContext.request.contextPath}/tag-types/core/for-each.jsp" 
          method="POST">
             Select your programming companions: <br/>
             C<input type="checkbox" name="langChoice" value="C"/><br/>
             C++<input type="checkbox" name="langChoice" value="C++"/><br/>
             Java<input type="checkbox" name="langChoice" value="Java"/><br/>
             C#<input type="checkbox" name="langChoice" value="C#"/><br/>
             PHP<input type="checkbox" name="langChoice" value="PHP"/><br/>
             Ruby<input type="checkbox" name="langChoice" value="Ruby"/><br/>
             jQuery<input type="checkbox" name="langChoice" value="jQuery"/><br/>
          <input type="submit" value="Submit"/>
   </form>
  <br/>
  <br/>
   You selected:
   <c:forEach var="lang" items="${paramValues.langChoice}">
        <font color="#00CC00"><c:out value="${lang}"/>,</font>
   </c:forEach>
  </body>
</html>

In the above example, we have few checkboxes to represent different programming choices. Upon user selection of these choices, we are iterating over the items user selected and displaying them using <c:forEach> tag.

 

Examples to demonstrate <c:forEach> attribute usage:

<c:forEach items="${countries}" var="country">
    <p>${country}</p>
<c:forEach>
In the above example we are displaying countries. Since it’s a simple type (String in this case) we can simply display its value. To display values from a list of POJOs, we iterate through the list and access each object’s property in order to display its value. The following example demonstrates this:

<c:forEach items="${studentList}" var="student">
    <p>${student.firstName}</p><br/>
    <p>${student.lastName}</p><br/>
    <p>${student.grade}</p><br/>
    <p>${student.dateOfBirth}</p><br/>
</c:forEach>

In the above example, we iterate over collection of student objects and displayed student properties. The attribute ‘var’ holds each object from the current iteration. Every time the variable defined in ‘var’ attribute will have a new object throughout the iteration.

In the some cases, we need to start iteration at a specified index or we may need to stop iterative at certain point. Also, we may need to iterate every alternate item in the collection. To deal with this kind of special cases <c:forEach> has additional attributes:

 



Begin

Iteration begins at the specified index. First item has an index of 0.

<c:forEach items="${schools}" var="school"  begin="4">
    School from index 4: ${school}
</c:forEach>
The above example displays school names from index 4 that means, from item 5 since index begins at 0.

 

End

Iteration ends at the specified index. The index is inclusive.

<c:forEach items="${schools}" var="school"  begin="4" end="8">
    School from index 4 until index 8: ${school}
</c:forEach>
The above example displays school names from index 4 that means, from item 5 since index begins at 0 until index 8. If the collection contains items more than 8, rest of the items will be ignored displaying only until index 8.

 

Step

To iterate over step items in the collection stating with the first item.

<c:forEach items="${schools}" var="school"  step="2">
    Every alternate school: ${school}
</c:forEach>
Above example displays every alternate school in the collection (i.e., 1,3,5,7 and so on).

 

varStatus

varStatus attribute essentially holds loop status object. We can do number of things with this attribute. One example is, if we want to do special things for last item in the collection we can use varStatus to access last item as shown in the below example:

<c:forEach items="${schools}" var="school"  varStatus="status">
    School from index 4 until index 8: ${school}
    ${not status.last ? ‘<hr/>’ : ‘<br/>’}
</c:forEach>
In the above example we are displaying school names with horizontal line for each school name. We avoided horizontal line for the last school name instead we had given a line break for the last item.

The variable given in the varStatus attribute is of type javax.servlet.jsp.jstl.core.LoopTagStatus.

 

Output:

forEach-demo

The selected choices are displaying using <c:forEach> tag.

 

Recommended Usage of JSTL <c:forEach> tag:

The <c:forEach> tag is useful to iterate over collections and to display their values. We can use attributes like begin, end, and step to perform iterations which start at a particular index or end at particular index or to step over items respectively. Using varStatus attribute which holds loop status, we can perform loop operations like checking whether the current iteration is the last iteration etc.

 

Other JSTL Core Tags:

catch  |  if |  choose   |  forTokens   |  import   |  out   |  param  |  redirect  |  remove   |  set  |  url


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#6Hector Talavera Jime2021-10-20 15:34
Como sustituir esto con jstl en spring?

Numero de boletos
Quote
#5Paco Murillo2020-11-24 07:35
Una pregunta, Como puedo hacer un forEach anidado para poder leer dos elementos de una tabla de una BD de MySQL? P.E. Si tengo una tabla que contiene anilla, especies y lugar como podría sacar las especies y el lugar donde se han visto, teneiendo encuenta que la misma ave ha sido vista en varios lugares.

Gracias.
Quote
#4Randolph Schreiner2020-05-21 20:02
Nice work. Thank you.
Quote
#3ram2015-05-14 01:14
As per my under standing.....json object we can't able to itreate using jstl.

For iteration of json obejct ...first u have to convert json boject into Collection and than after u can iterate it.
Quote
#2Nam2014-12-17 09:53
Hi Vipin Kumar,

Why do you think it's related to IE?

JSTL is processed on the server side, not the client side.
Quote