English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

<c:forEach> , <c:forTokens> tags

JSP Standard Tag Library

These tags encapsulate Java's for, while, do-while loop.

In contrast, the <c:forEach> tag is a more general tag because it iterates over objects in a collection.

<c:forTokens> tag splits a string into an array by specifying a 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>">

Attribute

The <c:forEach> tag has the following attributes:

Attribute Description Is Necessary Default Value
items The information to be looped through No None
begin The starting element (0=the first element,1= the second element) No 0
end The last element (0=the first element,1= the second element) No Last element
step The step length of each iteration No 1
var representing the variable name of the current entry No None
varStatus representing the variable name of the loop state No None

<c:forTokens> tag has similar attributes to <c:forEach> tag, but <c:forTokens> also has another attribute:

Attribute Description Is Necessary Default Value
delims Separator Yes None

<c:forEach>Example Demonstration

<%@ 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>

The running result is as follows:

Item 1
Item 2
Item 3
Item 4
Item 5

<c:forTokens>Example Demonstration

<%@ 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,w3codebox,taobao" delims="," var="name">
   <c:out value="${name}"/><p>
</c:forTokens>
</body>
</html>

The running result is as follows:

google
w3codebox
taobao

JSP Standard Tag Library