<c:forEach>, <c:forTokens> Tags
These tags encapsulate the for, while, and do-while loops in Java.
In comparison, the <c:forEach> tag is a more versatile tag because it iterates over objects in a collection.
The <c:forTokens> tag splits a string into an array using a specified delimiter and then iterates over them.
forEach Syntax Format
<c:forEach
items="<object>"
begin="<int>"
end="<int>"
step="<int>"
var="<string>"
varStatus="<string>">
...
forTokens Syntax Format
<c:forTokens
items="<string>"
delims="<string>"
begin="<int>"
end="<int>"
step="<int>"
var="<string>"
varStatus="<string>">
Attributes
The <c:forEach> tag has the following attributes:
| Attribute | Description | Required? | Default Value |
|---|---|---|---|
| items | The items to be iterated over | no | None |
| begin | Starting element (0=first element, 1=second element) | no | 0 |
| end | Last element (0=first element, 1=second element) | no | Last element |
| step | Step size for each iteration | no | 1 |
| var | Variable name representing the current item | no | None |
| varStatus | Variable name representing the loop status | no | None |
The <c:forTokens> tag has similar attributes to the <c:forEach> tag, but <c:forTokens> has another attribute:
| Attribute | Description | Required? | Default Value |
|---|---|---|---|
| delims | Delimiter | Yes | None |
<c:forEach> Example
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>c:forEach 标签实例</title>
</head>
<body>
<c:forEach var="i" begin="1" end="5">
Item <c:out value="${i}"/><p>
</c:forEach>
</body>
</html>
The output is as follows:
Item 1 Item 2 Item 3 Item 4 Item 5
<c:forTokens> Example
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>c:forTokens 标签实例</title>
</head>
<body>
<c:forTokens items="google,example,taobao" delims="," var="name">
<c:out value="${name}"/><p>
</c:forTokens>
</body>
</html>
The output is as follows:
google example taobao
Other Extensions
JSP Standard Tag Library