How do use <c:forEach> JSTL tag?

The <c:forEach> tag in the core JSTL tag library is a useful tag when we want to iterate over a collection of data such as array. It is commonly used to render a tabular data in our web pages in form of HTML table.

In the example below we display a weather data that we stored as two-dimensional array of string. After declaring and initializing the data with some value we put it into the request scope. Later on the <c:forEach> tag can use the data, iterates it row by row to form an HTML table. Our weather data consist of the date, condition and the high and low temperature.

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Weather Forecast</title>

    <style>
        table, th, td {
            border: 1px solid #000;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
<%
    String[][] data = {
            {"Oct 11", "Sunny", "30", "26"},
            {"Oct 12", "Sunny", "32", "28"},
            {"Oct 13", "Sunny", "31", "27"},
            {"Oct 14", "Partly Cloudy", "29", "25"},
            {"Oct 15", "Isolated T-Storms", "27", "25"}
    };
    request.setAttribute("weathers", data);
%>
<strong>5-Days Weather for Denpasar, Indonesia</strong>

<table>
    <tr>
        <th>DATE</th>
        <th>CONDITION</th>
        <th>TEMP. HIGH</th>
        <th>TEMP. LOW</th>
    </tr>
    <c:forEach var="weather" items="${weathers}">
        <tr>
            <td>${weather[0]}</td>
            <td>${weather[1]}</td>
            <td style="text-align: center">${weather[2]}℃</td>
            <td style="text-align: center">${weather[3]}℃</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

Our JSP page above creates the following output:

5-Days Weather for Denpasar, Indonesia

DATE CONDITION TEMP. HIGH TEMP. LOW
Oct 11 Sunny 30℃ 26℃
Oct 12 Sunny 32℃ 28℃
Oct 13 Sunny 31℃ 27℃
Oct 14 Partly Cloudy 29℃ 25℃
Oct 15 Isolated T-Storms 27℃ 25℃

Maven Dependencies

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.