JSP/Servlet | JSTL(JSP Standard Tag Library) | Loops <c:forEach>, <c:forTokens>
Loops are used to repeat the same task a specific number of times. In JSTL, let’s look at the most commonly used loop, <c:forEach>.
Directive declaration
To use loops, you need the JSTL core declaration at the top of the JSP page.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Loop using a <c:forEach> list
<c:forEach> receives a list and repeats as many times as the number of items in the list.
Attribute descriptions
| Item | Description | Required | Default |
|---|---|---|---|
| var | Variable name to use | Required | None |
| items | Collection object, such as List or Map | Required | |
| begin | Loop start index. If undefined, 0 | 0 | |
| end | Loop end index | Last index | |
| step | Number of indexes to skip each time it repeats | ||
| varStatus | Variable that provides loop status |
varStatus value descriptions
| Value | Return | Description |
|---|---|---|
| index | int | Index number pointing to the item defined in items. Starts from 0. |
| count | int | Indicates the current iteration number. Starts from 1. |
| first | boolean | Whether the current iteration is the first |
| last | boolean | Whether the current iteration is the last |
Usage examples
Example using all attributes
<c:forEach var="item" items="${items}" begin="0" end="10" step="1" varStatus="status">
<p>No.: ${status.index}</p>
<p>Book title: ${item.name}</p>
<p>Author: ${item.author}</p>
<p>Publisher: ${item.publisher}</p>
</c:forEach>
This example repeats from 0 to 10 for ${items} and displays the list.
Common usage example
<c:forEach var="item" items="${items}">
<p>No.: ${status.index}</p>
<p>Book title: ${item.name}</p>
<p>Author: ${item.author}</p>
<p>Publisher: ${item.publisher}</p>
</c:forEach>
Loop using <c:forTokens> tokens
This loop splits a string by a specific delimiter and repeats over the results. It works similarly to StringTokenizer in Java.
Attribute descriptions
| Item | Description | Required | Default |
|---|---|---|---|
| delims | Specific delimiter used to split the string | Required |
Usage example
<ol>
<c:forTokens var="item" items="apple,grape,banana,watermelon,strawberry" delims=",">
<li>Fruit: ${item}</li>
</c:forTokens>
</ol>
Put the string in items and the delimiter in delims. Each string separated by token can be obtained through the variable specified by var.