Popular Searches
Popular Course Categories
Popular Courses

Forwarding Requests Using RequestDispatcher

Forwarding Requests Using RequestDispatcher

HTTP Request and Response Handling

Forwarding Requests Using RequestDispatcher in Java Servlets

Course: Advanced Java Training

Topic: Forwarding Requests Using RequestDispatcher

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to RequestDispatcher

In Java web applications, a servlet often receives a request, performs some processing, and transfers control to another server-side resource to generate the final response. The RequestDispatcher interface provides a mechanism for forwarding requests to another servlet, a JSP page, or another supported resource within the web application.

For example, when a user submits a login form, a login servlet can validate the submitted credentials. If validation succeeds, it can forward the request to a dashboard JSP. If validation fails, it can forward the request to a login page containing an error message.

The RequestDispatcher interface belongs to the Servlet API and supports two primary operations: forward() and include(). This topic focuses on forwarding requests using forward().

2. Learning Objectives

  • Understand the purpose of the RequestDispatcher interface.
  • Learn how to obtain a RequestDispatcher object.
  • Understand the syntax and working of the forward() method.
  • Forward requests from one servlet to another servlet or JSP page.
  • Transfer data between servlets and JSP pages using request attributes.
  • Understand the difference between forwarding and redirecting.
  • Learn how to handle validation errors through request forwarding.
  • Identify common RequestDispatcher errors and their solutions.
  • Apply request forwarding in practical Java web applications.

3. What Is RequestDispatcher?

RequestDispatcher is an interface in the Servlet API that allows a servlet to transfer request processing to another server-side resource. The servlet container provides an implementation of this interface.

The target resource can process the existing request and generate the response that will be returned to the client.

Common Uses of RequestDispatcher

  • Forwarding a login request to a dashboard JSP after successful validation.
  • Forwarding invalid form submissions to a page displaying error messages.
  • Passing data from a servlet to a JSP page.
  • Transferring processing between multiple servlets.
  • Separating request-processing logic from presentation logic.
  • Building Model-View-Controller (MVC) applications.

4. Understanding the forward() Method

The forward() method transfers control from the current servlet to another resource on the server. The target resource continues processing the same request and produces the response.

Syntax

RequestDispatcher dispatcher =
        request.getRequestDispatcher("/target.jsp");

dispatcher.forward(request, response);

Explanation

  • request.getRequestDispatcher() obtains a dispatcher for the specified resource path.
  • "/target.jsp" represents the target resource within the web application.
  • forward(request, response) passes the current request and response objects to the target resource.
  • The target resource becomes responsible for generating the response.

Important: The response must not already be committed when forward() is called. If it has been committed, the container throws an IllegalStateException. Uncommitted buffered response output is cleared as part of forwarding.

5. How Request Forwarding Works

Request forwarding takes place entirely on the server. The browser sends a request to the original URL, and the servlet container internally dispatches that request to another resource.

Request Forwarding Workflow

  1. The client sends an HTTP request to a servlet.
  2. The servlet receives the request and performs initial processing.
  3. The servlet optionally stores data in request attributes.
  4. The servlet obtains a RequestDispatcher for the destination resource.
  5. The servlet invokes the forward() method.
  6. The container transfers control to the destination resource.
  7. The destination processes the request and generates the response.
  8. The browser receives the final response.

Example Workflow

Browser
   |
   | HTTP Request
   v
LoginServlet
   |
   | Validate Credentials
   v
RequestDispatcher.forward()
   |
   v
dashboard.jsp
   |
   | Generate HTML Response
   v
Browser

Unlike a redirect, forwarding does not normally require the browser to make a second HTTP request. The browser's address bar generally continues to show the original request URL.

6. Obtaining a RequestDispatcher Object

A servlet can obtain a RequestDispatcher object using methods provided by the Servlet API. The most common approach is to call getRequestDispatcher() on the request object.

Method 1: Using HttpServletRequest

RequestDispatcher dispatcher =
        request.getRequestDispatcher("/welcome.jsp");

dispatcher.forward(request, response);

This approach is commonly used when forwarding to a JSP, HTML page, or servlet identified by a path within the web application.

Method 2: Using ServletContext

RequestDispatcher dispatcher =
        getServletContext().getRequestDispatcher("/welcome.jsp");

dispatcher.forward(request, response);

The path supplied to ServletContext.getRequestDispatcher() must begin with a slash and is interpreted relative to the application's context root.

Method 3: Using a Named Dispatcher

RequestDispatcher dispatcher =
        getServletContext().getNamedDispatcher("ReportServlet");

if (dispatcher != null) {
    dispatcher.forward(request, response);
}

A named dispatcher looks up a servlet by its registered name. The name must match the servlet's configured name, and the lookup may return null if no matching servlet is available.

7. Forwarding a Request from One Servlet to Another

In a Java web application, one servlet can handle preliminary processing while another servlet performs a different task. This improves separation of responsibilities.

First Servlet: ProcessingServlet.java

import java.io.IOException;

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;

@WebServlet("/process")
public class ProcessingServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        String message = "Request processed successfully.";

        request.setAttribute("message", message);

        RequestDispatcher dispatcher =
                request.getRequestDispatcher("/result");

        dispatcher.forward(request, response);
    }
}

Second Servlet: ResultServlet.java

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/result")
public class ResultServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        String message =
                (String) request.getAttribute("message");

        try (PrintWriter out = response.getWriter()) {
            out.println("<!DOCTYPE html>");
            out.println("<html><body>");
            out.println("<h2>Result Page</h2>");
            out.println("<p>" + escapeHtml(message) + "</p>");
            out.println("</body></html>");
        }
    }

    private String escapeHtml(String value) {
        if (value == null) {
            return "";
        }

        return value.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace(""", "&quot;")
                .replace("'", "'");
    }
}

How This Example Works

  1. The browser sends a GET request to /process.
  2. ProcessingServlet creates a message and stores it as a request attribute.
  3. The servlet obtains a dispatcher for /result.
  4. The dispatcher forwards the request to ResultServlet.
  5. ResultServlet retrieves the message using getAttribute().
  6. The second servlet generates the HTML response.

The request attribute remains available during this server-side forward. Both servlet mappings are assumed to be deployed in the same web application.

8. Passing Data from a Servlet to a JSP Using RequestDispatcher

One of the most common uses of request forwarding is transferring data from a servlet to a JSP page. The servlet performs the processing, while the JSP presents the result to the user.

Servlet: WelcomeServlet.java

import java.io.IOException;

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;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        String username = "Rahul";

        request.setAttribute("username", username);
        request.setAttribute(
                "message", "Welcome to Advanced Java!");

        RequestDispatcher dispatcher =
                request.getRequestDispatcher("/welcome.jsp");

        dispatcher.forward(request, response);
    }
}

JSP Page: welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Welcome Page</title>
</head>
<body>
    <h1>Welcome, ${username}!</h1>
    <p>${message}</p>
</body>
</html>

Explanation

  • The servlet creates the username and welcome message.
  • The values are stored using request.setAttribute().
  • The dispatcher forwards the request to welcome.jsp.
  • The JSP reads the attributes using Expression Language (EL).
  • The generated page is returned to the browser.

For production applications, use context-appropriate output encoding when displaying dynamic values. JSP Expression Language alone should not be assumed to escape arbitrary untrusted text automatically.

9. Understanding Request Attributes During Forwarding

Request attributes are server-side objects associated with an HTTP request. They are particularly useful when transferring information from one servlet to another or from a servlet to a JSP.

Common Request Attribute Methods

Method Purpose
setAttribute(name, value) Stores an object in the request.
getAttribute(name) Retrieves a stored object.
removeAttribute(name) Removes an attribute from the request.
getAttributeNames() Returns an enumeration of request attribute names.

Example

request.setAttribute("studentName", "Priya");
request.setAttribute("course", "Advanced Java");

RequestDispatcher dispatcher =
        request.getRequestDispatcher("/student.jsp");

dispatcher.forward(request, response);

The destination JSP can retrieve the values through request attributes, provided they have not been removed or replaced.

Remember: Request attributes are different from request parameters. Parameters normally contain client-submitted string values, whereas attributes are objects set by server-side code.

10. Forwarding After Form Validation

RequestDispatcher is often used to handle form submissions. A servlet can validate user input and forward the request to an appropriate JSP page based on the result.

HTML Form: registration.html

<!DOCTYPE html>
<html>
<head>
    <title>Registration Form</title>
</head>
<body>
    <h2>Student Registration</h2>

    <form action="register" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>

        <button type="submit">Register</button>
    </form>
</body>
</html>

Servlet: RegisterServlet.java

import java.io.IOException;

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;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");
        String email = request.getParameter("email");

        if (name == null || name.isBlank()
                || email == null || email.isBlank()) {

            request.setAttribute(
                    "errorMessage",
                    "Name and email are required.");

            RequestDispatcher dispatcher =
                    request.getRequestDispatcher(
                            "/registration-error.jsp");

            dispatcher.forward(request, response);
            return;
        }

        request.setAttribute("studentName", name);
        request.setAttribute("studentEmail", email);

        RequestDispatcher dispatcher =
                request.getRequestDispatcher(
                        "/registration-success.jsp");

        dispatcher.forward(request, response);
    }
}

Success Page: registration-success.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Registration Successful</title>
</head>
<body>
    <h2>Registration Successful</h2>
    <p>Your registration details have been received.</p>
    <p>Name: ${studentName}</p>
    <p>Email: ${studentEmail}</p>
</body>
</html>

Error Page: registration-error.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Registration Error</title>
</head>
<body>
    <h2>Registration Failed</h2>
    <p>${errorMessage}</p>
    <a href="registration.html">Return to Registration</a>
</body>
</html>

This example demonstrates basic server-side validation and conditional forwarding. In a real application, validate the email format and business rules, encode dynamic output safely, and perform any required database operations before showing a success page.

11. RequestDispatcher forward() vs. sendRedirect()

Forwarding and redirecting both allow processing to continue at another resource, but they work differently.

Feature RequestDispatcher.forward() HttpServletResponse.sendRedirect()
Processing Transfers control internally on the server. Instructs the client to make a new request.
HTTP requests Normally one client request. Normally a redirect response followed by another request.
Browser URL Usually remains the original URL. Changes to the redirect destination.
Request attributes Remain available to the forwarded resource. Are not automatically carried into the new request.
Request parameters Remain available as part of the same request, subject to dispatcher behavior. Are not automatically preserved unless included or otherwise transferred.
Destination Normally a resource within the same web application context. Can direct the client to another application or external URL.
Common use Passing data to a JSP or another servlet. Redirecting after a successful form submission or navigating to another URL.

Forwarding Example

RequestDispatcher dispatcher =
        request.getRequestDispatcher("/dashboard.jsp");

dispatcher.forward(request, response);

Redirecting Example

response.sendRedirect(
        request.getContextPath() + "/dashboard");

Redirecting after a successful POST is commonly used in the Post/Redirect/Get pattern, which helps prevent accidental resubmission when a user refreshes the resulting page.

12. Forwarding vs. Including a Resource

The RequestDispatcher interface provides both forward() and include(). They serve different purposes.

Feature forward() include()
Purpose Transfers control to another resource to generate the response. Inserts the output of another resource into the current response.
Response generation The target resource takes responsibility for generating the response. The calling resource continues after the included output.
Typical use Servlet to JSP page navigation. Reusable header, footer, or content fragments.
Response headers and status The target resource can set them if the response is not committed. The included resource cannot change the response status or headers through the include dispatch.

Include Example

RequestDispatcher dispatcher =
        request.getRequestDispatcher("/header.jsp");

dispatcher.include(request, response);

// The calling servlet can continue producing the response.

Use forward() when another resource should handle the response. Use include() when the output of another resource should form part of the current response.

13. Important Rules When Using forward()

  • Call forward() before the response has been committed.
  • Use a valid target resource path.
  • Use the same request and response objects, or permitted Servlet API wrappers.
  • Do not assume that forwarding creates a new HTTP request from the browser.
  • Remember that request attributes are useful for passing server-side data.
  • Return from the current method after forwarding when further processing is not required.
  • Avoid writing response output before forwarding.
  • Validate data before passing it to the destination resource.
  • Ensure the destination resource does not create an unintended forwarding loop.
  • Use appropriate authorization checks for protected destination resources.

14. Understanding Forwarded Request Information

When a request is forwarded, the Servlet container exposes attributes describing the original request path. These can be useful for debugging, tracing, and request-processing logic.

Common Forward Attributes

Attribute Description
jakarta.servlet.forward.request_uri Original request URI.
jakarta.servlet.forward.context_path Original context path.
jakarta.servlet.forward.servlet_path Original servlet path.
jakarta.servlet.forward.path_info Original path information, if present.
jakarta.servlet.forward.query_string Original query string, if present.

Example

String originalUri = (String) request.getAttribute(
        "jakarta.servlet.forward.request_uri");

System.out.println("Original URI: " + originalUri);

These attributes are available when the request has undergone a forward dispatch and the relevant original information exists. They may be absent for requests that have not been forwarded.

15. RequestDispatcher in the MVC Architecture

Model-View-Controller (MVC) is a software design pattern that separates application responsibilities into three major components.

  • Model: Represents application data and business logic.
  • View: Presents information to the user, commonly through JSP pages in traditional Java web applications.
  • Controller: Receives requests, coordinates processing, and selects the appropriate view.

In a servlet-based MVC application, a controller servlet can process the request, call the appropriate service or model, store the results as request attributes, and forward the request to a JSP view.

MVC Example

Browser
   |
   v
Controller Servlet
   |
   v
Service / Model
   |
   v
Request Attributes
   |
   v
RequestDispatcher.forward()
   |
   v
JSP View
   |
   v
HTML Response

This structure makes applications easier to maintain because request handling, business logic, and presentation are separated. For larger applications, business logic should generally live in service classes rather than being embedded entirely in servlets.

16. Common Errors and Troubleshooting

Problem Possible Cause Solution
404 Not Found The target resource path is incorrect or the resource is not deployed. Verify the path, servlet mapping, and application context.
IllegalStateException The response was committed before forwarding. Set headers and forward before writing or flushing the response.
NullPointerException The dispatcher lookup returned null or an expected attribute was absent. Verify the resource path and check nullable values.
Request attribute is null The attribute was never set, was removed, or has a different name. Check the attribute name and processing order.
JSP does not display dynamic data Attribute names do not match or the wrong scope is being used. Check setAttribute(), JSP EL names, and request flow.
Infinite forwarding loop Two resources repeatedly forward to each other. Review dispatch conditions and ensure a clear stopping condition.
POST form is submitted again on refresh The browser is displaying the result of the original POST request. Consider the Post/Redirect/Get pattern after successful processing.
Destination cannot access expected data The data was stored in a local variable instead of a request attribute. Use request attributes or another appropriate data-transfer mechanism.

17. Best Practices for Request Forwarding

  • Use descriptive servlet mappings and clear destination paths.
  • Use request attributes to transfer data between a servlet and JSP.
  • Keep business logic in service classes rather than presentation pages.
  • Forward only after validation and required processing are complete.
  • Do not commit the response before forwarding.
  • Use redirects when the browser should navigate to a new URL.
  • Consider Post/Redirect/Get after successful state-changing POST requests.
  • Protect sensitive destinations with appropriate authentication and authorization.
  • Use safe output encoding when rendering user-controlled data.
  • Avoid forwarding loops and unintended repeated processing.
  • Keep internal error details out of user-facing pages.
  • Test forwarding behavior for valid input, invalid input, and missing resources.

18. Practical Exercises

Exercise 1: Forward to a Welcome Page

Create a servlet that sets a welcome message as a request attribute and forwards the request to a JSP page that displays it.

Exercise 2: Student Registration

Create a student registration form and a servlet that validates the submitted name and email. Forward valid submissions to a success page and invalid submissions to an error page.

Exercise 3: Servlet-to-Servlet Forwarding

Create two servlets. The first servlet should prepare data, while the second servlet should retrieve that data through request attributes and generate a response.

Exercise 4: Forward vs. Redirect

Implement two separate workflows: one using RequestDispatcher.forward() and another using sendRedirect(). Observe the browser URL and request behavior.

Exercise 5: MVC Mini Project

Build a simple product listing application in which a controller servlet retrieves product data from a service class and forwards it to a JSP view.

19. Interview Questions and Answers

Q1. What is RequestDispatcher in Java?

Answer: RequestDispatcher is a Servlet API interface that allows a server-side request to be forwarded to another resource or allows another resource's output to be included in the response.

Q2. What is the purpose of forward()?

Answer: The forward() method transfers control from one server-side resource to another using the same request and response objects, subject to the Servlet API rules.

Q3. How do you obtain a RequestDispatcher object?

Answer: It can be obtained through request.getRequestDispatcher(), getServletContext().getRequestDispatcher(), or a named dispatcher lookup.

Q4. What is the difference between forwarding and redirecting?

Answer: Forwarding occurs internally on the server, while redirecting sends an HTTP redirect response that causes the client to make another request.

Q5. Can request attributes be shared with a forwarded JSP?

Answer: Yes. Attributes stored using request.setAttribute() can be accessed by the target JSP during the same request.

Q6. Does forwarding change the browser URL?

Answer: Normally, no. The browser continues to display the original URL because forwarding does not instruct the browser to navigate to another URL.

Q7. Why can forward() throw IllegalStateException?

Answer: It can throw this exception if the response has already been committed before forwarding is attempted.

Q8. What is the difference between forward() and include()?

Answer: Forwarding transfers control to another resource to generate the response, whereas including inserts the target resource's output into the current response.

Q9. Can RequestDispatcher forward to another servlet?

Answer: Yes. A servlet can forward a request to another servlet using its mapped path or a named dispatcher.

Q10. Why is RequestDispatcher useful in MVC?

Answer: It allows a controller servlet to process requests, store model data as request attributes, and forward the request to a JSP view for presentation.

Q11. Does a forward create a new client request?

Answer: No. Forwarding is a server-side dispatch and normally takes place within the original client request.

Q12. What is the Post/Redirect/Get pattern?

Answer: It is a workflow in which a server processes a POST request and then redirects the client to a GET endpoint. This helps reduce accidental duplicate submissions when the result page is refreshed.

20. Quick Revision

  • RequestDispatcher is part of the Servlet API.
  • forward() transfers request processing to another server-side resource.
  • getRequestDispatcher() is commonly used to obtain a dispatcher.
  • Request attributes allow server-side data to be shared during forwarding.
  • Forwarding does not normally change the browser's address bar.
  • sendRedirect() causes the client to make a new request.
  • include() inserts another resource's output into the current response.
  • The response must not already be committed when forwarding occurs.
  • RequestDispatcher is commonly used in servlet-to-JSP MVC workflows.
  • Use safe output encoding and appropriate validation when displaying user-submitted data.

21. Conclusion

Forwarding requests using RequestDispatcher is an essential technique in Java Servlet development. It enables a servlet to transfer processing to another server-side resource without requiring the browser to make a new request.

By understanding getRequestDispatcher(), forward(), request attributes, and the differences between forwarding and redirecting, developers can build organized web applications with clear separation between controllers and presentation pages.

Combining request forwarding with server-side validation, safe output encoding, and the MVC design pattern helps make Java web applications more maintainable, reliable, and secure.


Learn Advanced Java with JustAcademy

Strengthen your practical knowledge of Java Servlets, RequestDispatcher, JSP, JDBC, session management, and enterprise web application development.

Explore the Advanced Java Training Course

Register for a Course Demo

Visit the JustAcademy Website

Previous Next
whatsapp