<c:forEach>, <c:forTokens> Tags
These tags encapsulate the for, while, do-while loops in Java.
By comparison, the <c:forEach> tag is more versatile as it iterates over objects in a collection.
The <c:forTokens> tag splits a string into an array using specified delimiters and then iterates over them.
forEach Syntax
<c:forEach
items="<object>"
begin="<int>"
end="<int>"
step="<int>"
var="<string>"
varStatus="<string>">
...
forTokens Syntax
<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 | Information to be looped over | No | None |
begin | Starting element (0=first element, 1=second element) | No | 0 |
end | Ending 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 with an additional 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 Tag Example</title>
</head>
<body>
<c:forEach var="i" begin="1" end="5">
Item <c:out value="${i}"/><p>
</c:forEach>
</body>
</html>
Output:
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 Tag Example</title>
</head>
<body>
<c:forTokens items="google,tutorialpro,taobao" delims="," var="name">
<c:out value="${name}"/><p>
</c:forTokens>
</body>
</html>
Output:
google
tutorialpro
taobao