Nearby lessons
17 of 30JSTL - Iteration Tags
- Use <c:forEach> with begin/end/step for numeric loops
- Iterate over arrays and collections with <c:forEach> items attribute
- Use varStatus for iteration metadata (first, last, count, index)
- Tokenize strings with <c:forTokens>
- Understand JSTL SQL and Functions library overview
The JSTL Iteration Tags provide loop constructs for iterating over collections, arrays, and strings. This lesson covers <c:forEach> and <c:forTokens> with complete code examples, plus an overview of the JSTL SQL and Functions libraries.
Iteration Tags Overview
JSTL provides two iteration tags in the core library:
| Tag | Description | Attributes |
|---|---|---|
<c:forEach> | General purpose for loop — iterates over numeric ranges, arrays, and collections | items, begin, end, step, var, varStatus |
<c:forTokens> | Specialized for string tokenization — splits strings by delimiter | items, delims, begin, end, step, var, varStatus |
c:forEach — Numeric Loop
Form 1 — Simple numeric loop:
<c:forEach begin="1" end="10" step="1">
<h1>Learning JSTL is very easy!</h1>
</c:forEach>
This prints the message 10 times.
Attributes:
| Attribute | Description | Default |
|---|---|---|
begin | Index where the loop starts | — |
end | Index where the loop terminates | — |
step | Counter increment between iterations | 1 |
Examples:
<c:forEach begin="1" end="10" step="2"> <!-- Runs 5 times -->
<c:forEach begin="4" end="0" step="-1"> <!-- INVALID: step cannot be negative -->
c:forEach — With var Attribute
Form 2 — Using var to access the counter:
The <c:forEach> tag maintains an internal counter variable. Use var to access it.
<c:forEach begin="1" end="10" step="2" var="count">
<h1>Learning JSTL is very easy!!! --- ${count}</h1>
</c:forEach>
This prints the message 5 times with counter values 1, 3, 5, 7, 9.
Note: The var variable is local to the loop — it cannot be accessed outside the loop body.
c:forEach — Iterating Arrays and Collections
Form 3 — Iterating over arrays and collections:
<c:forEach items="collection_object" var="current_object">
body
</c:forEach>
The items attribute accepts a Collection, Array, Map, or String. The current item is stored in the var variable.
Example — Print all elements of an array:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String[] s = {"A", "B", "C", "D"};
pageContext.setAttribute("s", s);
%>
<c:forEach items="${s}" var="obj">
<h1>The current Object is: ${obj}</h1>
</c:forEach>
Example — Print all request headers:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table border="2">
<c:forEach items="${header}" var="hdr">
<tr>
<td>${hdr.key}</td>
<td>${hdr.value}</td>
</tr>
</c:forEach>
</table>
Example — Print all request parameters:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table border="2">
<c:forEach items="${param}" var="p">
<tr>
<td>${p.key}</td>
<td>${p.value}</td>
</tr>
</c:forEach>
</table>
c:forEach — varStatus
Form 4 — Using varStatus for iteration metadata:
The varStatus attribute provides an object of type javax.servlet.jsp.core.TagLoopStatus with methods describing the current iteration state.
Example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="durga,pavan,ravi,shiva" varStatus="status">
<h1>
Is it First Iteration: ${status.first}<br>
The current Object is: ${status.current}<br>
Number of iterations already completed: ${status.count}<br>
Is it Last Iteration: ${status.last}<br>
<hr>
</h1>
</c:forEach>
TagLoopStatus methods:
| Method | Returns |
|---|---|
getCurrent() | The current item being processed |
getIndex() | The current index (counter value) |
getCount() | Number of iterations already performed (1-based) |
isFirst() | true if this is the first iteration |
isLast() | true if this is the last iteration |
getBegin() | The begin index |
getEnd() | The end index |
getStep() | The step (increment) value |
c:forTokens — String Tokenization
<c:forTokens> is a specialized version of <c:forEach> that splits strings by a delimiter — similar to Java's StringTokenizer.
Basic form:
<c:forTokens items="durga.pavan.shiva.ravi" delims="." var="x">
<h1>Hello: ${x}</h1>
</c:forTokens>
With begin, end, step, and varStatus:
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forTokens items="one,two,three,four,five,six" delims="," var="x" begin="2" end="5" step="1">
<h1>Current Token is: ${x}</h1>
</c:forTokens>
This iterates over tokens at indices 2, 3, 4, 5 (tokens: three, four, five, six).
c:forEach vs c:forTokens:
| Attribute | c:forEach | c:forTokens |
|---|---|---|
items | Collection, Array, Map, or String | String only |
delims | Not applicable | Delimiter string (required) |
begin | ✓ | ✓ |
end | ✓ | ✓ |
step | ✓ | ✓ |
var | ✓ | ✓ |
varStatus | ✓ | ✓ |
<c:forTokens> is considered a specialized version of <c:forEach> — it only works with String items.
JSTL SQL Library Overview
The JSTL SQL Library provides tags for communicating with databases. Add this taglib directive to use it:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
Important SQL tags:
| Tag | Description |
|---|---|
<sql:setDataSource> | Create a database connection (DataSource) |
<sql:query> | Execute a SELECT query |
<sql:update> | Execute INSERT, UPDATE, or DELETE |
<sql:param> | Provide parameter values for PreparedStatement |
<sql:dateParam> | Provide date values for PreparedStatement |
<sql:transaction> | Group queries into a transaction (All or None) |
Example — Select query:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<sql:setDataSource var="ds" driver="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:XE"
user="scott" password="tiger" />
<sql:query dataSource="${ds}" var="result">
SELECT * from Employees
</sql:query>
<h1>
<c:forEach items="${result.rows}" var="row">
${row.eno} -- ${row.ename} -- ${row.esal} -- ${row.eaddr}<br>
</c:forEach>
</h1>
Example — Insert:
<sql:update dataSource="${ds}" var="count">
insert into employees values(500, 'Lasya', 5000, 'hyd')
</sql:update>
<h1>The number of rows inserted: ${count}</h1>
Example — Transaction:
<sql:transaction dataSource="${ds}">
<sql:update>
update employees set esal=esal-1000 where ename='durga'
</sql:update>
<sql:update>
update employees set esal=esal+1000 where ename='sunny'
</sql:update>
</sql:transaction>
Note: It is not recommended to use JSTL SQL Library in production JSP pages. JSP is meant for presentation logic, not business or database logic.
JSTL Functions Library Overview
The JSTL Functions Library provides tags for general string manipulation. Add this taglib directive:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Example — String operations:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="s" value="Hello Learning JSTL is Very Easy" />
<h1>
Length: ${fn:length(s)}<br>
In Upper Case: ${fn:toUpperCase(s)}<br>
In Lower Case: ${fn:toLowerCase(s)}<br>
Sub String from index 6 to 15: ${fn:substring(s, 6, 15)}<br>
Is s contains JSTL: ${fn:contains(s, "JSTL")}<br>
Is s starts with Hello: ${fn:startsWith(s, "Hello")}<br>
Is s ends with Easy: ${fn:endsWith(s, "Easy")}<br>
</h1>
Example — Split and Join:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="data" value="sunny,mallika,veena,reshmi,anasuya" />
<c:set var="s" value="${fn:split(data, ',')}" />
<h1>
Result of split method:<br>
<c:forEach items="${s}" var="s1">
${s1}<br>
</c:forEach>
<c:set var="result" value="${fn:join(s, '-')}" />
Result of Joining: ${result}
</h1>
- c:forEach handles both numeric ranges and collection iteration
- c:forTokens is a specialized string tokenizer
- varStatus provides rich iteration metadata