How do I include content from another servlet or JSP?

To include the content of one servlet or JSP into another, you can use the functionality provided by the RequestDispatcher interface in Jakarta Servlet (previously Javax Servlet). The two primary methods for including content are:

  1. Using RequestDispatcher.include():
    This method includes the response of another servlet or JSP within the response of the current servlet or JSP.

  2. Using <jsp:include /> Tag:
    This is specifically used in JSP to include another JSP or servlet dynamically.


1. Using RequestDispatcher.include() in servlets

You can use the include() method of the RequestDispatcher to include the content of another servlet or JSP. Here’s how it works:

  • Steps:
    1. Obtain a RequestDispatcher object for the target servlet or JSP.
    2. Use the include() method to include its output.

Example Code:

package org.kodejava.servlet;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;

@WebServlet("/include")
public class IncludeServletExample extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        var out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Content from Main Servlet</h1>");

        // Getting RequestDispatcher for another servlet or JSP
        RequestDispatcher dispatcher = request.getRequestDispatcher("/example");

        // Including content
        dispatcher.include(request, response);

        out.println("<h1>This is after including the content</h1>");
        out.println("</body></html>");
    }
}

2. Using <jsp:include /> in JSP

This is used to include either static or dynamic content from another JSP or servlet directly within a JSP page.

  • Syntax:
<jsp:include page="URL or Path" />

The page attribute specifies the relative URL or path of the servlet or JSP to be included.

Example Code:

<html>
<body>
  <h1>Content from Main JSP</h1>

  <!-- Include another servlet or JSP -->
  <jsp:include page="includedJspPage.jsp" />

  <h1>This is after including the content</h1>
</body>
</html>

Important Notes

  • Differences between include() and forward():
    • include(): Includes the response from the target servlet/JSP into the current response. The execution continues after including the content.
    • forward(): Forwards the request to another servlet/JSP. The control does not return to the original servlet/JSP.
  • Context-relative paths:
    • When specifying the path in RequestDispatcher (e.g., /example), always use context-relative paths (starting with a / relative to the root of the web application).
  • Dynamic Content:
    • The target servlet or JSP can contain dynamic content, as it is executed when included.

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How to create JSP error page to handle exceptions?

In this example you will learn how to handle exceptions in JSP page. JSP have a build-in mechanism for error handling which is a special page that can be used to handle every error in the web application. To define a page as an error page we use the page directive and enable the isErrorPage attribute by setting the value to true.

Here is an example of a JSP error page:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Error Page</title>
</head>
<body>
<h1>An error has occurred.</h1>

<div style="color: #F00;">
    Error message: <%= exception.toString() %>
</div>
</body>
</html>

We have defined the error page. The next steps is how to tell other JSP pages to use the error page to handle errors when uncaught exception occurred. To do this we again use the page directive. Set the errorPage attribute of this directive to point to the error page. For instance in the example below we set it to errorPage.jsp.

If we try to access the errorTest.jsp as shown in the snippet below. It will throw an exception because we try to convert an invalid string into a number. Because we are not handling the error in the page the error page will come up and show the exception messages.

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page errorPage="/errorPage.jsp" %>
<html lang="en">
<head>
    <title>My Sample Page</title>
</head>
<body>
<h1>This page throws an error:</h1>

<%
    int number = Integer.parseInt("Hello, World!");
%>
</body>
</html>
JSP Error Page Demo

JSP Error Page Demo

How to include page dynamically in JSP page?

In this example we are going to learn how to use <jsp:include> action. This action can be used to include resource dynamically to our JSP pages. For example the resource can be another JSP page, a servlet or event a static html pages. But to make it enable to be processed as a JSP page, such as accepting parameters, we must use the .jsp as the file extension. If we use other extension such as .jspf, it will be processed as a static page.

The other things to note is that using the <jsp:include> action will process the page inclusion at the request time. This is why we can pass parameters to the included page using the <jsp:param>. The value can be read by obtaining the parameter from the request object or using expression language variable param.

But if we use the <%@ include %> directive the inclusion of the page happen when it translated into a Servlet. See the following example about the <%@ include %> directive: How do I include a page fragment into JSP?

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

Lorem Ipsum

<jsp:include page="jspf/footer.jsp">
    <jsp:param name="year" value="2021"/>
</jsp:include>

</body>
</html>

Below is the content of our footer.jsp page. In this page we display the footer information with a parameter read from the request object.

<%@ page contentType="text/html;charset=UTF-8" %>
<hr/>
Copyright © ${param["year"]} Kodejava.org. All rights reserved.

This example will give you the following result in the browser:

JSP Include Action Demo

JSP Include Action Demo

How do I forward request to another page in JSP?

To forward a request from one page to another JSP page we can use the <jsp:forward> action. This action has a page attribute where we can specify the target page of the forward action. If we want to pass parameter to another page we can include a <jsp:param> in the forward action. But make sure that the forward page is a JSP page to enable the parameters to be processed.

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

<jsp:forward page="message.jsp">
    <jsp:param name="message" value="Welcome!"/>
</jsp:forward>

</body>
</html>

And here is how to read the parameters in the message.jsp.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Message: ${param["message"]}</title>
</head>
<body>
Message: ${param["message"]}
</body>
</html>
jsp:forward Demo

jsp:forward Demo

When you access the jspForward.jsp page in the web browser what you will see is the content of the message.jsp page. This is because the <jsp:forward> action forward your request to the message.jsp before returning the response back to the browser for display.

How do I use jsp:useBean action in JSP pages?

In this example you will learn how to use the <jsp:useBean>. We can use the useBean action to create a scripting variables. To define the variable name we use the id attribute of this action. The class attribute define the type of this variable. We can also define the scope of the variable using the scope attribute.

As an example in the code snippet below we create a variable name now and declare it to hold a java.util.Date instance. And then we use a JSP expression to print out the value.

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

<jsp:useBean id="now" class="java.util.Date"/>

Now is: <%= now %>

</body>
</html>
jsp:useBean Demo

jsp:useBean Demo