How do I forward requests with RequestDispatcher?

In Java, the RequestDispatcher is used to forward a client’s request to another resource, such as a servlet, JSP, or HTML file. This is common when you want to break down the processing of a request into multiple components.

Syntax to Use RequestDispatcher

The RequestDispatcher interface provides two main methods to forward or include content:

  1. forward(ServletRequest request, ServletResponse response): Forwards the request to another resource.
  2. include(ServletRequest request, ServletResponse response): Includes the content of another resource in the response.

Steps to Forward Requests

  1. Get the RequestDispatcher object:
    Use ServletRequest.getRequestDispatcher(String path) to obtain a RequestDispatcher instance. The path can be relative or absolute.

  2. Forward the request:
    Call the forward() method on the RequestDispatcher object to forward the request and response to another resource.

Example of Using RequestDispatcher

Here’s an example of using the RequestDispatcher to forward a request to another servlet or JSP:

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/forwardExample")
public class ForwardExampleServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Add some attributes to the request
        request.setAttribute("message", "This is a forwarded request");

        // Get the RequestDispatcher for the target resource
        RequestDispatcher dispatcher = request.getRequestDispatcher("/target.jsp");

        // Forward the request and response
        dispatcher.forward(request, response);
    }
}

What Happens When You Forward?

  1. The forward() method hands over control of the request to the specified resource.
  2. The original request and response objects are passed along to the next resource.
  3. The client’s browser does not see a new request or URL change. The forward happens entirely on the server.

Example of the Target Resource (target.jsp)

Here’s an example target.jsp that receives the forwarded request:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>Forwarded Page</title>
    </head>
    <body>
        <h1>Forwarded Page</h1>
        <p>Message: ${message}</p>
    </body>
</html>

Key Points to Remember

  1. Forward Happens Internally:
    The URL in the browser doesn’t change, and the operations happen on the server side.

  2. Avoid Committing the Response:
    You cannot forward() the request if the response has already been committed (e.g., if you’ve written something to the response output already).

  3. Relative and Absolute Paths:

    • A path starting with / is absolute (relative to the web application root).
    • A path without / is relative to the current request path.
  4. Forward vs Redirect:
    • Forward happens on the server side; the browser is unaware.
    • Redirect happens by sending a response back to the client, requiring the client to make a new request.

Maven dependencies

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

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.