Popular Searches
Popular Course Categories
Popular Courses

Implementing Iteration with JSTL

Implementing Iteration with JSTL

JSP Expression Language, JSTL, and Custom Tags

Implementing Iteration with JSTL

Course: Advanced Java Training

Topic: Implementing Iteration with JSTL

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Iteration with JSTL

Iteration is the process of repeatedly executing a block of code or processing elements in a collection. In Java web applications, iteration is commonly required to display student records, product lists, employee details, order histories, search results, and other dynamic data on web pages.

JSTL (JSP Standard Tag Library) provides iteration tags that allow developers to repeat JSP content without embedding traditional Java loops inside JSP scriptlets. The most commonly used iteration tag is <c:forEach>. Another useful tag, <c:forTokens>, iterates over tokens separated by specified delimiter characters.

These tags work with JSP Expression Language (EL), which accesses values prepared by Servlets, controllers, JavaBeans, and other application components.

Example

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<c:forEach var="course" items="${courses}">
    <p>${course}</p>
</c:forEach>

If the courses attribute contains several course names, the loop produces one paragraph for each item.

2. Learning Objectives

After completing this topic, you should be able to:

  • Explain the purpose of iteration in JSP applications.
  • Understand the syntax and attributes of <c:forEach>.
  • Iterate over arrays, Lists, Sets, Maps, and other supported data sources.
  • Use varStatus to access iteration status information.
  • Control iteration with begin, end, and step.
  • Use <c:forTokens> to process delimited strings.
  • Combine JSTL iteration with EL, JavaBeans, and conditional tags.
  • Build a dynamic table using data passed from a Servlet.
  • Identify common iteration errors and apply best practices.

3. What Is Iteration?

Iteration means processing a sequence of items one at a time. For example, an online store may have a list of products that must be displayed on a product page. Instead of writing separate HTML markup for every product, the application can use a loop to generate the markup dynamically.

Example Without JSTL

A JSP scriptlet might contain a Java loop such as:

<%
    String[] courses = {"Java", "JSP", "Servlets"};

    for (String course : courses) {
        out.println("<p>" + course + "</p>");
    }
%>

This approach mixes Java code with HTML and can make the page difficult to maintain. It can also produce unsafe output if untrusted values are inserted without proper escaping.

Example Using JSTL

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<c:forEach var="course" items="${courses}">
    <p><c:out value="${course}" /></p>
</c:forEach>

The JSTL version is more declarative and keeps the presentation code separate from the Java logic that prepares the data.

4. Introduction to the c:forEach Tag

The <c:forEach> tag repeats its body for each element in a supported collection or for a specified numerical range. It is the primary JSTL tag for general-purpose iteration.

Basic Syntax

<c:forEach var="item" items="${collection}">
    <!-- Repeated content -->
</c:forEach>

Important Attributes

Attribute Description Example
items Specifies the collection, array, or other supported source to iterate over. items="${students}"
var Names the variable representing the current item. var="student"
varStatus Names the variable that provides information about the current iteration. varStatus="status"
begin Specifies the starting index when iterating over a collection, or the starting number for a numeric loop. begin="0"
end Specifies the ending index or number. The end value is inclusive. end="4"
step Specifies the interval between processed items or numbers. step="2"

The var and varStatus attributes are literal variable names, not EL expressions. For example, use var="student", not var="${student}".

5. Iterating Over an Array

An array stores a fixed number of elements of the same declared type. JSTL can iterate over object arrays and primitive arrays, making it suitable for displaying simple collections of values.

Example

Suppose a Servlet stores an array of course names in request scope:

String[] courses = {"Core Java", "Advanced Java", "JSP", "Servlets"};
request.setAttribute("courses", courses);

The JSP page can display the array as follows:

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<h2>Available Courses</h2>
<ul>
    <c:forEach var="course" items="${courses}">
        <li><c:out value="${course}" /></li>
    </c:forEach>
</ul>

Each array element is assigned to the variable course during one iteration. The tag then renders one list item for that element.

6. Iterating Over a List

A Java List is a collection that preserves element order and supports index-based access. Lists are commonly used to store records retrieved from a database or prepared by a service layer.

Example: Student List

A Servlet can prepare a List of student objects and forward it to a JSP page.

List<Student> students = studentService.getAllStudents();
request.setAttribute("students", students);
request.getRequestDispatcher("/WEB-INF/views/students.jsp")
       .forward(request, response);

The JSP view can iterate over the list:

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<h2>Student Records</h2>
<ul>
    <c:forEach var="student" items="${students}">
        <li>
            Name: <c:out value="${student.name}" />,
            Course: <c:out value="${student.course}" />
        </li>
    </c:forEach>
</ul>

The expressions ${student.name} and ${student.course} access the corresponding readable properties of each Student object.

7. Iterating Over a Set

A Set stores unique elements according to its implementation. Some Set implementations preserve insertion order, while others do not guarantee a particular iteration order.

Example

Set<String> technologies = new LinkedHashSet<>();
technologies.add("Java");
technologies.add("JSP");
technologies.add("Servlets");

request.setAttribute("technologies", technologies);

JSP:

<ul>
    <c:forEach var="technology" items="${technologies}">
        <li><c:out value="${technology}" /></li>
    </c:forEach>
</ul>

The loop displays each unique technology in the Set. If a specific display order matters, choose a collection implementation or sort the data appropriately before forwarding it to the view.

8. Iterating Over a Map

A Java Map stores key-value pairs. When a Map is supplied to <c:forEach>, each iteration exposes an entry with accessible key and value properties.

Example

Map<String, String> studentDetails = new LinkedHashMap<>();
studentDetails.put("Name", "Priya");
studentDetails.put("Course", "Advanced Java");
studentDetails.put("City", "Mumbai");

request.setAttribute("studentDetails", studentDetails);

JSP:

<table border="1" cellpadding="8" cellspacing="0">
    <tr>
        <th>Field</th>
        <th>Value</th>
    </tr>
    <c:forEach var="entry" items="${studentDetails}">
        <tr>
            <td><c:out value="${entry.key}" /></td>
            <td><c:out value="${entry.value}" /></td>
        </tr>
    </c:forEach>
</table>

The variable entry represents the current Map entry. The key is accessed through ${entry.key}, and the corresponding value through ${entry.value}.

9. Iterating Over a Numeric Range

The <c:forEach> tag can also repeat content a fixed number of times without using the items attribute. In this form, begin and end define the numerical range.

Example

<c:forEach var="number" begin="1" end="5">
    <p>Number: ${number}</p>
</c:forEach>

This produces five paragraphs containing the numbers 1 through 5.

Example: Generate Table Rows

<table border="1" cellpadding="8" cellspacing="0">
    <c:forEach var="row" begin="1" end="4">
        <tr>
            <td>Row ${row}</td>
            <td>Sample data ${row}</td>
        </tr>
    </c:forEach>
</table>

Numeric-range iteration is useful for simple repeated structures. When displaying real business records, use the collection form instead.

10. Controlling Iteration with begin, end, and step

The begin, end, and step attributes allow the developer to process a range or a subset of a collection.

10.1 Using begin and end with a Collection

<c:forEach var="product"
           items="${products}"
           begin="1"
           end="3">
    <p><c:out value="${product.name}" /></p>
</c:forEach>

When used with a collection, the first item has index 0. Therefore, this example processes the items at indexes 1, 2, and 3, if those indexes exist.

10.2 Using step

<c:forEach var="number" begin="1" end="10" step="2">
    <p>${number}</p>
</c:forEach>

The numeric sequence is 1, 3, 5, 7, and 9.

10.3 Combining Range Attributes with a Collection

<c:forEach var="product"
           items="${products}"
           begin="0"
           end="8"
           step="2">
    <p><c:out value="${product.name}" /></p>
</c:forEach>

This processes every second item in the specified index range. Make sure the collection contains the expected number of items.

11. Understanding varStatus

The varStatus attribute exposes an object that provides information about the current iteration. This is useful when displaying row numbers, identifying the first or last item, or applying alternating styles.

Common varStatus Properties

Property Description
index Zero-based index of the current item within the underlying iteration.
count One-based count of the current iteration.
first Boolean value indicating whether the current iteration is the first processed item.
last Boolean value indicating whether the current iteration is the last processed item.
current The current item being processed.
begin The configured starting index or value, when applicable.
end The configured ending index or value, when applicable.
step The configured iteration step, when applicable.

Example: Display Row Numbers

<table border="1" cellpadding="8" cellspacing="0">
    <tr>
        <th>No.</th>
        <th>Student Name</th>
    </tr>
    <c:forEach var="student"
               items="${students}"
               varStatus="status">
        <tr>
            <td>${status.count}</td>
            <td><c:out value="${student.name}" /></td>
        </tr>
    </c:forEach>
</table>

The count property starts at 1, making it convenient for user-facing row numbers. The index property starts at 0.

Example: Mark the First and Last Items

<c:forEach var="course"
           items="${courses}"
           varStatus="status">
    <p>
        <c:if test="${status.first}">First: </c:if>
        <c:out value="${course}" />
        <c:if test="${status.last}"> - Last item</c:if>
    </p>
</c:forEach>

This example shows how iteration status can change the presentation of individual items without writing Java logic in the JSP page.

12. Introduction to the c:forTokens Tag

The <c:forTokens> tag iterates over tokens in a string separated by one or more delimiter characters. It is useful for simple delimited text values, such as a comma-separated list of technology names.

Syntax

<c:forTokens items="${stringValue}"
             delims=","
             var="token">
    <!-- Repeated content -->
</c:forTokens>

Example

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<c:set var="topics" value="JSP,Servlets,JSTL,EL" />

<ul>
    <c:forTokens items="${topics}"
                 delims=","
                 var="topic">
        <li><c:out value="${topic}" /></li>
    </c:forTokens>
</ul>

The output contains one list item for each token separated by a comma.

Multiple Delimiter Characters

<c:set var="topics" value="JSP,Servlets;JSTL EL" />

<c:forTokens items="${topics}"
             delims=",; "
             var="topic">
    <p><c:out value="${topic}" /></p>
</c:forTokens>

In c:forTokens, the delims attribute represents a set of delimiter characters. Each listed character separates tokens; the value is not treated as one complete multi-character separator.

13. Difference Between c:forEach and c:forTokens

Feature c:forEach c:forTokens
Primary purpose Iterates over collections, arrays, supported objects, or numeric ranges. Iterates over tokens in a delimited string.
items value Can be a List, Set, array, Map, or other supported source. Uses a string containing tokens.
delims attribute Not used. Defines delimiter characters.
Common use Displaying database records or object collections. Processing simple delimited strings.
Iteration status Supports varStatus. Supports varStatus.

14. Combining Iteration with Conditional Tags

Iteration is often combined with JSTL conditional tags to display different output depending on each item's values.

Example: Display Student Results

<c:forEach var="student" items="${students}">
    <p>
        <c:out value="${student.name}" />:
        <c:choose>
            <c:when test="${student.marks ge 75}">
                Distinction
            </c:when>
            <c:when test="${student.marks ge 40}">
                Pass
            </c:when>
            <c:otherwise>
                Needs Improvement
            </c:otherwise>
        </c:choose>
    </p>
</c:forEach>

The outer c:forEach processes each student. Inside the loop, c:choose determines which result message to display.

15. Building a Dynamic HTML Table

A common use of JSTL iteration is displaying records in an HTML table. The following example illustrates how a product list can be rendered dynamically.

Example Data Preparation in a Servlet

List<Product> products = productService.getAllProducts();
request.setAttribute("products", products);
request.getRequestDispatcher("/WEB-INF/views/products.jsp")
       .forward(request, response);

JSP Page

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<!DOCTYPE html>
<html>
<head>
    <title>Product List</title>
</head>
<body>
    <h1>Available Products</h1>

    <c:choose>
        <c:when test="${empty products}">
            <p>No products are available.</p>
        </c:when>
        <c:otherwise>
            <table border="1" cellpadding="8" cellspacing="0">
                <tr>
                    <th>No.</th>
                    <th>Product Name</th>
                    <th>Price</th>
                </tr>
                <c:forEach var="product"
                           items="${products}"
                           varStatus="status">
                    <tr>
                        <td>${status.count}</td>
                        <td><c:out value="${product.name}" /></td>
                        <td><c:out value="${product.price}" /></td>
                    </tr>
                </c:forEach>
            </table>
        </c:otherwise>
    </c:choose>
</body>
</html>

This page checks whether the collection is empty and then either displays a message or renders the product table. Each row is generated from one product object.

16. Nested Iteration in JSTL

Nested iteration means placing one loop inside another. It is useful when data has a hierarchical structure, such as departments containing employees or categories containing products.

Example: Categories and Products

Suppose each category object exposes a readable name property and a products collection.

<c:forEach var="category" items="${categories}">
    <h3><c:out value="${category.name}" /></h3>

    <ul>
        <c:forEach var="product" items="${category.products}">
            <li><c:out value="${product.name}" /></li>
        </c:forEach>
    </ul>
</c:forEach>

The outer loop processes categories, while the inner loop processes products belonging to the current category. Ensure the nested collection is available and appropriately initialized.

17. Empty Collections and Null Values

Applications should handle missing or empty data gracefully. If the items expression evaluates to null, c:forEach performs no iterations. A collection with no elements also produces no repeated content.

Example

<c:choose>
    <c:when test="${empty students}">
        <p>No student records found.</p>
    </c:when>
    <c:otherwise>
        <c:forEach var="student" items="${students}">
            <p><c:out value="${student.name}" /></p>
        </c:forEach>
    </c:otherwise>
</c:choose>

This avoids showing an empty list without explanation. The controller should still handle errors in data retrieval and provide appropriate application-level feedback.

18. Iteration Performance and Pagination

Although JSTL makes iteration convenient, rendering a very large collection directly into one JSP response can produce slow pages and large HTML documents.

  • Use pagination: Retrieve and display a limited number of records per page.
  • Filter data before rendering: Apply search and filtering criteria in the service or database layer where appropriate.
  • Sort in the appropriate layer: Prepare records in the desired order before forwarding to JSP.
  • Avoid unnecessary nested loops: Large nested collections can generate excessive output and processing work.
  • Use efficient database access: Avoid loading large numbers of records when the page needs only a small subset.
  • Keep JSP focused on display: Do not execute database queries or complicated calculations inside an iteration tag.

19. Common Errors and Troubleshooting

Problem Possible Cause Solution
Loop displays no items The collection is null, empty, or stored under the wrong attribute name. Verify the controller sets the correct request attribute before forwarding.
Bean properties are blank Incorrect property name or missing accessible getter. Check the JavaBean property names and getter methods.
JSTL tag is not recognized Missing dependency or incorrect tag-library URI. Check the JSTL version, runtime implementation, and taglib directive.
Incorrect number of iterations Unexpected begin, end, or step values. Remember that collection indexes begin at zero and the end index is inclusive.
Wrong row numbering Using zero-based index instead of one-based count. Use status.count for user-facing numbering.
Map values do not display Incorrect use of key or value properties. Use ${entry.key} and ${entry.value}.
Token output differs from expectation Delimiter characters are misunderstood. Remember that each character in delims is a delimiter.
Page loads slowly Too many records or expensive nested iterations. Use pagination, filtering, and optimized data retrieval.
Unexpected output or HTML behavior Unescaped user-controlled values are rendered directly. Use suitable output escaping and validate input on the server.

20. Security Best Practices

  • Use c:out for ordinary HTML text when output escaping is required.
  • Do not assume that HTML escaping protects values inserted into JavaScript, CSS, URLs, or other contexts.
  • Validate user input on the server before using it in application logic.
  • Keep authentication and authorization checks in the backend rather than relying on JSP display conditions.
  • Do not expose passwords, tokens, confidential data, or sensitive internal identifiers in rendered collections.
  • Retrieve only the records the current user is authorized to view.
  • Keep database queries and access-control decisions outside JSP pages.
  • Use a suitable pagination strategy when displaying large or sensitive datasets.

21. Practical Exercises

  1. Course List: Create a String array containing five course names and display them using c:forEach.
  2. Student Table: Pass a List of Student objects from a Servlet to JSP and display their names and marks.
  3. Numbered Rows: Use varStatus to display row numbers starting at 1.
  4. Numeric Range: Print numbers from 1 to 20 using begin and end.
  5. Step Iteration: Display every second number between 1 and 15.
  6. Map Iteration: Display a Map of student details as key-value rows.
  7. Token Processing: Split a comma-separated string of technologies using c:forTokens.
  8. Conditional Results: Combine c:forEach with c:choose to display student grades.
  9. Empty List Handling: Display a friendly message when a collection is empty.
  10. Product Catalog: Create a product table with row numbering, formatted values, and empty-data handling.

22. Mini Project: Dynamic Student Records Table

Objective: Develop a small MVC-style web application that displays student records using Servlets, JavaBeans, JSP Expression Language, and JSTL iteration.

Project Requirements

  • Create a Student JavaBean containing student ID, name, course, and marks.
  • Create a Servlet that retrieves or prepares a list of students.
  • Store the list as a request attribute and forward to a JSP page.
  • Use c:forEach to display each student in an HTML table.
  • Use varStatus to display a row number.
  • Use c:choose to display a pass or needs-improvement result.
  • Use c:out to escape ordinary HTML text output where appropriate.
  • Handle empty results gracefully.
  • Keep business logic and database access in backend components.

Expected Outcome

The completed application should display a dynamic table that updates according to the student collection supplied by the Servlet. It should demonstrate collection iteration, iteration status, conditional rendering, and the separation of application logic from presentation.

23. Interview Questions and Answers

Q1. What is iteration in JSTL?

Answer: Iteration is the process of repeating JSP content for items in a collection or across a specified range. JSTL provides tags such as c:forEach and c:forTokens for this purpose.

Q2. What is the purpose of c:forEach?

Answer: It repeats its body for each item in a supported collection or for values within a specified numerical range.

Q3. What is the purpose of the items attribute?

Answer: It identifies the data source that the loop processes, such as a List, Set, array, or Map.

Q4. What is the var attribute?

Answer: It names the scoped variable representing the current item during an iteration.

Q5. What is varStatus?

Answer: It exposes an iteration status object containing information such as the current index, iteration count, and whether the current item is the first or last.

Q6. What is the difference between index and count?

Answer: The index is zero-based, while count is one-based. Use count when displaying row numbers to users.

Q7. How do begin, end, and step work?

Answer: They control the range of values or collection indexes processed. The end value is inclusive, and step determines the interval between processed values or items.

Q8. What is the difference between c:forEach and c:forTokens?

Answer: c:forEach iterates over collections, arrays, supported objects, or numerical ranges. c:forTokens iterates over tokens separated by specified delimiter characters in a string.

Q9. Can JSTL iterate over a Map?

Answer: Yes. Each iteration exposes a Map entry whose key and value can be accessed using ${entry.key} and ${entry.value}.

Q10. What happens if the items attribute is null?

Answer: The loop performs no iterations. Developers should handle missing or empty data explicitly when the user needs feedback.

Q11. Why is JSTL iteration preferred over scriptlets?

Answer: JSTL makes JSP pages more readable, reduces embedded Java code, and supports better separation between application logic and presentation.

Q12. How can iteration be combined with conditions?

Answer: Place tags such as c:if or c:choose inside the body of c:forEach to render different content for each item.

24. Quick Revision Checklist

  • c:forEach is the main JSTL iteration tag.
  • c:forTokens processes delimiter-separated strings.
  • items identifies the data source for collection iteration.
  • var names the current item variable.
  • varStatus exposes index, count, first, last, and related iteration details.
  • Collection indexes begin at zero.
  • The end value is inclusive.
  • step controls the interval between processed items or values.
  • Maps expose entries with key and value properties.
  • Use EL and JSTL together to build dynamic JSP pages.
  • Use c:out where appropriate for escaped HTML text output.
  • Handle null collections and empty results gracefully.
  • Keep business logic and database access in backend components.
  • Use pagination when displaying large collections.

25. Conclusion

JSTL iteration is an essential technique for building dynamic Java web pages. The c:forEach tag simplifies the display of arrays, Lists, Sets, Maps, and numeric ranges, while c:forTokens is useful for processing simple delimited strings. Attributes such as varStatus, begin, end, and step provide additional control over how data is rendered.

By combining JSTL with EL, JavaBeans, and Servlet controllers, developers can create readable and maintainable JSP views without embedding Java loops in the page. Practice the examples and exercises to strengthen your understanding of iteration in Advanced Java web development.


Further Learning

Explore the Advanced Java Training Course to learn more about Servlets, JSP, JSTL, Expression Language, JDBC, and enterprise Java development.

To discuss course details or request a demonstration, visit the JustAcademy Course Demo Registration Page.

Visit the JustAcademy official website for additional training resources.

Reference Documentation

Previous Next
whatsapp