ZetCode

JSTL forEach tag

last modified July 13, 2020

JSTL forEach tutorial shows how to use the forEach tag from the JSTL library.

JSTL

JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags that provide the core functionality common to many JSP applications.

forEach tag

JSTL <c:forEach> tag is a basic iteration tag. It iterates over various Java collection types.

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

forEach taglib declaration

The <c:forEach> tag belongs to the core JSTL tags.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

To use the tag, we need to include this declaration.

JSTL Maven artifact

To use the JSTL library, we need the following Maven dependency:

<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

forEach tag example

The following JSP page contains the <c:forEach> tag. In addiction to <c:forEach> tag, we also use <c:out> for displaying variables.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <c:forEach var="counter" begin="1" end="8">
            <c:out value="${counter}"/>
        </c:forEach>
    </body>
</html>

The example shows values 1..8 in the output.

forEach tag example II

The next JSP example reads parameters sent from a link.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        
        <a href="target.jsp?name=Jane&age=23&occupation=accountant">Show page</a>
        
    </body>
</html>

The index.html page contains a link that sends three parameters to the target.jsp page.

target.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <c:forEach var="par" items="${param}">

            <c:out value="${par.key}"/>: <c:out value="${par.value}"/> <br>

        </c:forEach>
    </body>
</html>

The JSP page receives parameters in the implicit param object, which is a map.

<c:forEach var="par" items="${param}">

    <c:out value="${par.key}"/>: <c:out value="${par.value}"/> <br>

</c:forEach>

We go over the map and print the key/value pairs.

forEach tag example III

The HTML <select> is a control that provides a menu of options. With its multiple attribute, the user can select multiple values form the control.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Languages</title>
        <meta charset="UTF-8">
    </head>
    <body>

        <form action="target.jsp">
            <div>Select languages:</div>

            <select name="languages" size="7" multiple="multiple">
                <option value='Ada'>Ada</option>
                <option value='C'>C</option>
                <option value='C++'>C++</option>
                <option value='Cobol'>Cobol</option>
                <option value='Eiffel'>Eiffel</option>
                <option value='Objective-C'>Objective-C</option>
                <option value='Java'>Java</option>
            </select>

            <button type="submit">Submit</button>

        </form>

    </body>
</html>

We create a <select> control that contains seven values. When we submit the form, the selected values are sent to the target.jsp file.

target.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Languages</title>
    </head>
    <body>
        <c:forEach items="${paramValues.languages}" var="lang">
            <c:out value="${lang}"/>
        </c:forEach>
    </body>
</html>

The valuues from the <select> control are available from the implicit paramValues object, which is a map. The key is the request parameter name (languages) and the values are in an array of strings.

<c:forEach items="${paramValues.languages}" var="lang">
    <c:out value="${lang}"/>
</c:forEach>

We go over the array and print its elements.

forEach tag example IV

The following example displays data in an HTML table.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <p>
            <a href="MyServlet">Show all cities</a>
        </p>
    </body>
</html>

In the index.html page we have a link that calls MyServlet. The servlet loads data with a service method and dispatches to the JSP page.

com/zetcode/City.java
package com.zetcode.bean;

public class City {
    
    private Long id;
    private String name;
    private int population;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public City(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }
}

This is the City class; it contains id, name, and population attributes.

com/zetcode/MyServlet.java
package com.zetcode.web;

import com.zetcode.bean.City;
import com.zetcode.service.CityService;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        
        List<City> cities = CityService.getAllCities();
        
        request.setAttribute("cities", cities);
        
        request.getRequestDispatcher("showCities.jsp").forward(request, response);
    }
}

The servlet reads data with CityService.getAllCities, sets the list object to the attributes with setAttribute, and forwards to the showCities.jsp.

com/zetcode/CityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.ArrayList;
import java.util.List;

public class CityService {
    
    public static List<City> getAllCities() {
    
       List<City> cities = new ArrayList<>();
        
        cities.add(new City(1L, "Bratislava", 432000));
        cities.add(new City(2L, "Budapest", 1759000));
        cities.add(new City(3L, "Prague", 1280000));
        cities.add(new City(4L, "Warsaw", 1748000));
        cities.add(new City(5L, "Los Angeles", 3971000));
        cities.add(new City(6L, "New York", 8550000));
        cities.add(new City(7L, "Edinburgh", 464000));
        cities.add(new City(8L, "Berlin", 3671000));
        
        return cities;
    }
}

The getAllCities method returns a list of cities.

showCities.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Cities</title>
    </head>
    <body>
        <h2>Cities</h2>
        
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Population</th>
                </tr>
            </thead>
            
            <tbody>
                <c:forEach items="${cities}" var="city">
                <tr>
                    <td>${city.id}</td>
                    <td>${city.name}</td>
                    <td>${city.population}</td>
                </tr>
                </c:forEach>   
            </tbody>
        </table>
    </body>
</html>

In the showCities.jsp, we display the cities in the HTML table with the <c:forEach> tag.

<td>${city.id}</td>
<td>${city.name}</td>
<td>${city.population}</td>

The attributes are read from the city object with the dot operator.

In this tutorial, we have covered the <c:forEach> tag from the JSTL library.