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

How do I write and read object from HTTP Session?

In this post you will learn how to write and read object from HTTP Session in JavaServer Page. The first example that we are looking at is using the classic JSP scriptlet, this is a very old way to work with JSP, but it is good for you to know a history. We write a JSP scriptlet inside the <% %> symbols. We can use the provided session object. To set an attribute in the session object we use the setAttribute(String name, Object value) method. In the example we create an attribute called loginDate and set the value to the current date.

To read a value from a session object we use the getAttribute(String name) method. This method return a type of Object, so we need to cast it to the original object. In this case we cast it to a java.util.Date. And then we print out the value read from the session object.

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Session Write</title>
</head>
<body>
<%
// Creates a session attribute named login-date to store a java.util.Date.
session.setAttribute("loginDate", new Date());

// Read back the java.util.Date object from the session attribute.
Date loginDate = (Date) session.getAttribute("loginDate");
%>
Login Date: <%= loginDate %>
</body>
</html>

The second way that you can use to read values from session object is using the JSP Expression Language (EL). It looks like the following code snippet. You can use the sessionScope implicit object combined with the session attribute name. You can see two ways to use the sessionScope object below. The simplest one is to use the attribute name as the EL expression, and it will look smartly to find the value in the available scope.

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Session Read EL</title>
</head>
<body>
<p>Login Date: ${sessionScope.loginDate}</p>

<p>Login Date: ${sessionScope["loginDate"]}</p>

<p>Login Date: ${loginDate}</p>
</body>
</html>

How do I include a page fragment into JSP?

In this example you can learn how to include a JSP fragment into another JSP page. This is a common practice when creating a web application where we usually have a navigation section, the main content and the footer of a web page. Using the include directive make it simpler to maintain the fragment of a web page, which mean that when we need to change for example the footer section we just need to alter the footer include file and all the page that includes it will get the benefit.

The page inclusion that using the include direction will occur at page translation time, it is when the JSP page is translated into a Servlet by JSP container. We can use any file extension name for the JSP fragment used by the include directive. In this example we use the .jspf extension which is short for JSP Fragment.

Here is an example of JSP with include directive.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Include Directive</title>
</head>
<body>

<div id="header">
    <%@ include file="/include/common/header.jspf" %>
</div>

<div id="content">
    Main application content goes here!
</div>

<div id="footer">
    <%@ include file="/include/common/footer.jspf" %>
</div>

</body>
</html>

header.jspf fragment.

Header
<hr/>

footer.jspf fragment.

<hr/>
Footer

How do I format a date in a JSP page?

This example show how to format date in JSP using format tag library. We create a date object using the <jsp:useBean> taglib. To format the date we use the <fmt:formatDate> taglib. We assign the value attribute to the date object, set the type attribute as date and define the pattern how the date will be formatted.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Date Format</title>
</head>
<body>
<jsp:useBean id="date" class="java.util.Date"/>
Today is: <fmt:formatDate value="${date}" type="date" pattern="dd-MMM-yyyy"/>
</body>
</html>

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I get web application context path in JSP?

This example show you how to obtain web application context path in JSP using Expression Language (EL) feature of JSP. To get the context path we can utilize the pageContext, it is an implicit object that available on every JSP pages. From this object you can get access to various object such as:

  • servletContext
  • session
  • request
  • response

To get the context path value you will need to read it from the request.contextPath object. This contextPath can be useful for constructing a path to you web resources such as CSS, JavaScript and images. Libraries that you’ll need to enable the JSP Expression Language (EL) in your JSP Pages, which usually already included in a Servlet container such as Apache Tomcat.

Here is our context-path.jsp file.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Context Path</title>
</head>

<body>
Web Application Context Path = ${pageContext.request.contextPath}
</body>
</html>

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central