JSTL Core <c:forEach>, <c:forTokens> Tag

Advertisements


These tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet. The <c:forEach> tag is the more commonly used tag because it iterates over a collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the tokens.

Attribute:

The <c:forEach> tag has following attributes:

AttributeDescription RequiredDefault
itemsInformation to loop overNoNone
beginElement to start with (0 = first item, 1 = second item, ...)No0
endElement to end with (0 = first item, 1 = second item, ...)NoLast element
stepProcess every step itemsNo1
varName of the variable to expose the current itemNoNone
varStatusName of the variable to expose the loop statusNoNone

The <c:forTokens> tag has similar attributes as <c:forEach> except one additional attribute delims which specifies sharacters to use as delimiters.

AttributeDescription RequiredDefault
delimsCharacters to use as delimitersYesNone

Example for <c:forEach>:

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

This would produce following result:

Item 1
Item 2
Item 3
Item 4
Item 5

Example for <c:forTokens>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:forTokens> Tag Example</title>
</head>
<body>
<c:forTokens items="Zara,nuha,roshy" delims="," var="name">
   <c:out value="${name}"/><p>
</c:forTokens>
</body>
</html>

This would produce following result:

Zara
nuha
roshy


Advertisements
Advertisements