How do use c:forEach JSTL tag?

Category: taglib / jstl, viewed: 979 time(s).

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 use 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" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Weather Page</title>
</head>
<body>
<%
    String[][] data = {
            {"Nov 6", "Sunny", "32", "26"},
            {"Nov 7", "Sunny", "32", "26"},
            {"Nov 8", "Sunny", "32", "26"},
            {"Nov 9", "Partly Cloudy", "32", "26"},
            {"Nov 10", "Isolated T-Storms", "32", "26"}
    };
    request.setAttribute("weathers", data);
%>
<strong>5-Days Weather for Denpasar, Indonesia</strong>

<table border="1">
    <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 align="center">${weather[2]}&#8451;</td>
            <td align="center">${weather[3]}&#8451;</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
Nov 6 Sunny 32℃ 26℃
Nov 7 Sunny 32℃ 26℃
Nov 8 Sunny 32℃ 26℃
Nov 9 Partly Cloudy 32℃ 26℃
Nov 10 Isolated T-Storms 32℃ 26℃
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats