Latest web development tutorials

<C: forEach>, <c: forTokens> tag

JSP Standard Tag Library JSP Standard Tag Library

These labels are encapsulated in Java for, while, do-while loop.

In contrast, <c: forEach> tag is more generic label, because it is a collection of objects iteration.

<C: forTokens> tag by specifying a delimiter separated string into an array then iterate 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

<C: forEach> tag has the following attributes:

Attributes description If necessary Defaults
items Information to be circulated no no
begin Element start (0 = first element, the second element = 1) no 0
end The last element (0 = first element, the second element = 1) no Last element
step Each iteration step no 1
var Variable name represents the current entry no no
varStatus Representative circulation state variable name no no

<C: forTokens> tag and <c: forEach> tag has similar properties, but <c: forTokens> has another attribute:

Attributes description If necessary Defaults
delims Separator Yes no

<C: forEach> instance demo

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

Results are as follows:

Item 1
Item 2
Item 3
Item 4
Item 5

<C: forTokens> Demo Examples

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

Results are as follows:

google
w3big
taobao

JSP Standard Tag Library JSP Standard Tag Library