How do I forward to other page using <jsp:forward>?

The <jsp:forward/> tag forward user request to other page. For example, a user request page1.jsp and in this page the server found a <jsp:forward page="page2.jsp"/>. The server immediately stop the processing of page1.jsp and jump to the page2.jsp.

Let see an example of using <jsp:forward/> tag.

page1.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page 1</title>
</head>
<body>
<strong>This is page 1</strong>

<jsp:forward page="page2.jsp"/>
</body>
</html>

page2.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Page 2</title>
</head>
<body>
<strong>This is page 2</strong>
</body>
</html>

When you try to run the example above by accessing the URL http://localhost:8080/forward/page1.jsp you are going to see the content of page2.jsp instead of page1.jsp. It’s happen because on the server side page1.jsp forward your request to the page2.jsp. But if you look at your browser URL address it will still point to page1.jsp.

Here is the directory structure of our example:

.
├─ pom.xml
└─ src
   └─ main
      └─ webapp
         └─ forward
            └─ page1.jsp
            └─ page2.jsp

Maven Dependencies

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

Maven Central

How do I include other pages using <jsp:include>?

The <jsp:include/> tag is use for including another page fragment of a JSP page into another page. This is useful when you have a common page such as header, footer or a menu that applied to many of all of your pages.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><jsp:include/> Demo</title>
</head>
<body>
<div id="header">
    <jsp:include page="include/common/header.jsp"/>
</div>

<div id="main">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna
    aliqua.
</div>

<div id="footer">
    <jsp:include page="include/common/footer.jsp"/>
</div>
</body>
</html>

Here are the page fragment of the header.jsp, footer.jsp and menu.jsp. All of them are placed in the common folder in the same location with the index.jsp file.

header.jsp

<strong><jsp:include/> Demo</strong>
<hr/>
<jsp:include page="menu.jsp"/>

footer.jsp

<hr/>
© 2021 Kode Java Org

menu.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<a href="<c:url value="/index.jsp"/>">HOME</a>

When you access your page (http://localhost:8080/jsp-include-tag.jsp) from the servlet container such as Apache Tomcat you’ll have a complete display of a page that contains header, menu, content and footer.

Here is the directory structure of our example:

.
.
├─ pom.xml
└─ src
   └─ main
      └─ webapp
         ├─ include
         │  └─ common
         │     ├─ footer.jsp
         │     ├─ header.jsp
         │     └─ menu.jsp
         ├─ jsp-include-tag.jsp
         └─ index.jsp

Maven Dependencies

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

Maven Central

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