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:
- Using
RequestDispatcher.include()
:
This method includes the response of another servlet or JSP within the response of the current servlet or JSP. -
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:
- Obtain a
RequestDispatcher
object for the target servlet or JSP. - Use the
include()
method to include its output.
- Obtain a
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).
- When specifying the path in
- 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>