Popular Searches
Popular Course Categories
Popular Courses

Redirecting Requests Using sendRedirect()

Redirecting Requests Using sendRedirect()

HTTP Request and Response Handling

Redirecting Requests Using sendRedirect() in Java Servlets

Course: Advanced Java Training

Topic: Redirecting Requests Using sendRedirect()

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Request Redirection

Request redirection is a technique used in Java web applications to send a browser or client to another URL. It is commonly used after form submissions, successful login operations, logout processes, and navigation between pages.

In Java Servlet programming, the sendRedirect() method of the HttpServletResponse interface allows a servlet to instruct the client to make a new request to another location.

For example, after a user submits a registration form, the servlet may process the submitted information and redirect the browser to a success page.

  • HttpServletRequest: Represents the incoming HTTP request.
  • HttpServletResponse: Represents the response sent by the server.
  • sendRedirect(): Sends a redirect response that instructs the client to navigate to another URL.
  • Redirect destination: The URL that the client requests after receiving the redirect response.

2. Learning Objectives

After completing this topic, learners will be able to:

  • Understand the purpose of request redirection.
  • Use response.sendRedirect() in Java Servlets.
  • Redirect users to pages within the same application.
  • Redirect users to external websites.
  • Understand the difference between forwarding and redirecting.
  • Implement redirects after form submissions and authentication.
  • Handle context paths and redirect URLs correctly.
  • Prevent open-redirect vulnerabilities and common redirection errors.

3. What Is sendRedirect()?

The sendRedirect() method belongs to the HttpServletResponse interface in the Java Servlet API. It sends a temporary redirect response to the client, normally using HTTP status code 302 Found in the traditional one-argument Servlet API.

The browser or client then makes another HTTP request to the URL specified by the redirect response.

Syntax

response.sendRedirect("destinationURL");

Example

response.sendRedirect("welcome.jsp");

In this example, the servlet instructs the browser to request the destination represented by welcome.jsp. The exact interpretation of a relative URL depends on the URL-resolution rules described by the Servlet API.

4. How sendRedirect() Works

Request redirection involves communication between the server and the client. The server does not directly transfer the existing request to the destination resource.

  1. The browser sends a request to a servlet.
  2. The servlet receives and processes the request.
  3. The servlet calls response.sendRedirect() with the destination URL.
  4. The servlet container sends a redirect response, typically with status code 302 and a Location header.
  5. The browser reads the redirect response.
  6. The browser makes a new request to the destination URL.
  7. The destination resource processes the new request and returns a response.

Request Flow

Browser
   |
   | 1. Request /login
   v
LoginServlet
   |
   | 2. Validate credentials
   |
   | 3. sendRedirect("/app/dashboard")
   v
HTTP Redirect Response
   |
   | 4. Browser receives Location header
   v
Browser Requests Dashboard
   |
   v
Dashboard Resource
   |
   | 5. Return dashboard response
   v
Browser Displays Dashboard

The important point is that a redirect normally creates a new client request. The original request parameters and request attributes are not automatically carried into that new request.

5. Basic Servlet Example Using sendRedirect()

The following example demonstrates how to redirect a user from one servlet to another page.

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("/start")
public class StartServlet extends HttpServlet {

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

        response.sendRedirect(
            request.getContextPath() + "/welcome"
        );
    }
}

Explanation:

  • @WebServlet("/start") maps the servlet to the /start URL within the application.
  • doGet() handles incoming HTTP GET requests.
  • request.getContextPath() returns the application's context path.
  • sendRedirect() tells the browser to request the destination URL.

For example, if the application context path is /myapp, the redirect destination becomes /myapp/welcome.

Use the jakarta.servlet imports for modern Jakarta Servlet applications. Older Java EE projects generally use the corresponding javax.servlet imports and a compatible servlet container.

6. Redirecting to a JSP Page

A servlet can redirect the browser to a JavaServer Pages (JSP) resource. This approach may be used when a user needs to navigate to a separate page after an operation.

Servlet Code

@WebServlet("/success")
public class SuccessRedirectServlet extends HttpServlet {

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

        response.sendRedirect(
            request.getContextPath() + "/success.jsp"
        );
    }
}

Example success.jsp

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Success Page</title>
</head>
<body>
    <h1>Operation Completed Successfully</h1>
    <p>Your request has been processed.</p>
</body>
</html>

The browser makes a separate request to the JSP. If the JSP is stored under WEB-INF, the browser cannot access it directly, so a server-side forward is usually appropriate instead.

7. Redirecting to Another Servlet

One servlet can redirect a client to another servlet. This is useful for separating responsibilities such as authentication, order processing, and dashboard rendering.

First Servlet

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

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

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

Destination Servlet

@WebServlet("/dashboard")
public class DashboardServlet extends HttpServlet {

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

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

        response.getWriter().println(
            "<h1>Welcome to the Dashboard</h1>"
        );
    }
}

When the browser accesses /process, the first servlet sends a redirect. The browser then requests /dashboard, where the second servlet generates the response.

8. Redirecting to an External Website

The sendRedirect() method can also redirect a client to an external website using an absolute URL.

@WebServlet("/external")
public class ExternalRedirectServlet extends HttpServlet {

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

        response.sendRedirect(
            "https://www.justacademy.co/"
        );
    }
}

When a user requests this servlet, the browser is instructed to navigate to the specified external website.

External redirects should be used carefully. Never redirect to an arbitrary URL supplied by a user without validation, because this can create an open-redirect vulnerability.

9. Using sendRedirect() After Form Submission

One of the most common applications of redirection is handling HTML form submissions. After processing a form, a servlet can redirect the user to a confirmation page.

HTML Form

<form action="register" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username"
        name="username" required>
    <button type="submit">Register</button>
</form>

Registration Servlet

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

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

        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");

        if (username == null || username.isBlank()) {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "Username is required."
            );
            return;
        }

        // Validate and save registration data here.

        response.sendRedirect(
            request.getContextPath() + "/registration-success"
        );
    }
}

Success Servlet

@WebServlet("/registration-success")
public class RegistrationSuccessServlet extends HttpServlet {

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

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

        response.getWriter().println(
            "<h2>Registration completed successfully.</h2>"
        );
    }
}

This example demonstrates the Post/Redirect/Get (PRG) pattern. After processing the POST request, the servlet redirects the browser to a GET endpoint. Refreshing the success page therefore normally repeats the GET request instead of resubmitting the original form.

Important: In a real registration system, redirect only after the registration operation has actually succeeded. Handle database errors and validation failures separately.

10. Understanding the Post/Redirect/Get Pattern

Post/Redirect/Get is a web application design pattern that separates a form-submission request from the page displayed after processing.

How PRG Works

  1. The browser submits form data using POST.
  2. The servlet validates and processes the submitted data.
  3. The servlet redirects the browser to a GET endpoint.
  4. The browser requests the new URL using GET.
  5. The destination endpoint displays the result.

Benefits of PRG

  • Reduces accidental duplicate form submissions caused by refreshing the result page.
  • Provides a clean URL for the final page.
  • Separates form processing from page display.
  • Improves navigation after successful operations.

PRG does not guarantee that a transaction will execute only once. Critical operations such as payments and order creation may also require idempotency controls, duplicate-request detection, and appropriate transaction management.

11. Understanding Redirect Status Codes

Traditional Servlet API versions use HTTP status code 302 for the one-argument sendRedirect(String location) method. The browser uses the redirect response to determine the next request.

Status Code Name Purpose
301 Moved Permanently Indicates a permanent change in the resource location.
302 Found Indicates a temporary redirect; the traditional Servlet redirect method uses this status.
303 See Other Directs the client to retrieve another resource, typically using GET.
307 Temporary Redirect Temporarily redirects while preserving the HTTP method.
308 Permanent Redirect Permanently redirects while preserving the HTTP method.

In the traditional Servlet API, sendRedirect() does not let the caller choose a redirect status code directly. Newer Servlet API versions provide additional overloads that support explicit redirect status codes. Check the API documentation for the container and version used by your project.

12. Relative URLs and Absolute URLs

Understanding URL formats helps prevent redirection errors.

12.1 Relative URL

response.sendRedirect("welcome.jsp");

A relative URL without a leading slash is resolved relative to the current request URI according to the Servlet API's URL-resolution rules.

12.2 Context-Relative Application URL

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

This approach builds a URL using the application's context path and is generally useful when redirecting to a resource within the same web application.

12.3 Server-Root-Relative URL

response.sendRedirect("/welcome");

A URL beginning with a single slash is interpreted relative to the servlet container's root, not automatically relative to the current web application's context. If the application is deployed under a context such as /myapp, this URL may point to the wrong location.

12.4 Absolute URL

response.sendRedirect(
    "https://www.justacademy.co/"
);

An absolute URL includes the scheme and host and is appropriate when redirecting to an external destination.

13. Difference Between sendRedirect() and forward()

Both redirection and forwarding can move processing to another resource, but they operate differently.

Feature sendRedirect() forward()
Execution Client-side navigation triggered by a redirect response. Server-side transfer using a RequestDispatcher.
HTTP request The browser makes a new request. The existing request is reused.
Browser URL Changes to the redirect destination. Normally remains the same.
Request attributes Not automatically preserved in the new request. Remain available in the forwarded request.
External website Can redirect to an external website. Cannot forward directly to an external website.
Typical use Navigation after form submission or to another URL. Passing request data to a JSP or another server-side resource.

Forward Example

request.setAttribute(
    "message",
    "Welcome to the application."
);

request.getRequestDispatcher("/welcome.jsp")
       .forward(request, response);

Redirect Example

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

Use forwarding when the next resource should process the same request. Use redirection when the client should navigate to another URL and issue a new request.

14. Redirecting After Login

Redirection is commonly used after successful authentication to send a user to a dashboard or another protected resource.

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

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

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // Demonstration only. Use a secure authentication
        // service and password hashing in a real application.
        boolean authenticated =
            "student".equals(username)
            && "demo".equals(password);

        if (authenticated) {
            request.getSession(true)
                   .setAttribute("username", username);

            response.sendRedirect(
                request.getContextPath() + "/dashboard"
            );
        } else {
            response.sendRedirect(
                request.getContextPath() + "/login-failed"
            );
        }
    }
}

This is a simplified teaching example, not production authentication code. A real system must verify credentials securely, rotate the session identifier after authentication, protect against CSRF where applicable, and enforce authorization on protected resources.

Do not assume that redirecting to a dashboard protects it. The dashboard endpoint must independently check the user's authentication and authorization status.

15. Redirecting with Query Parameters

A servlet can include query parameters in the redirect URL when the destination needs simple navigation information.

String destination =
    request.getContextPath()
    + "/result?status=success";

response.sendRedirect(destination);

The destination servlet can read the parameter through request.getParameter("status").

Do not place passwords, access tokens, sensitive personal information, or confidential business data in query parameters. URLs may be stored in browser history, server logs, analytics systems, and referrer information.

16. Preserving Session Information During Redirection

A redirect creates a new request, but session information can remain available when the browser continues to send the session cookie and the session is still valid.

HttpSession session = request.getSession();
session.setAttribute("message", "Profile updated");

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

The destination servlet can retrieve the session attribute if the same session is maintained.

HttpSession session = request.getSession(false);

String message = null;

if (session != null) {
    message = (String) session.getAttribute("message");
}

For one-time notifications, developers can retrieve and remove the message after displaying it. Session handling must account for expiry, logout, and concurrent requests.

17. Common Errors When Using sendRedirect()

Error Cause Solution
IllegalStateException The response has already been committed. Call sendRedirect() before writing or flushing the response body.
404 Not Found The destination URL is incorrect. Verify the servlet mapping, context path, and destination resource.
Redirect to the wrong path A leading slash was interpreted relative to the container root. Include request.getContextPath() for application-relative redirects.
Form data is missing The redirect starts a new request. Store appropriate non-sensitive state in a session or use another suitable design.
Redirect loop Two endpoints repeatedly redirect to each other. Review authentication checks and destination logic.
Duplicate form submissions The user refreshes a page that was generated by POST. Use the Post/Redirect/Get pattern and idempotency controls where needed.
Open redirect An untrusted destination URL is accepted. Use allowlisted destinations or validate against trusted internal paths.

18. Security Best Practices

  • Never redirect to an arbitrary user-supplied URL without validation.
  • Use allowlists when users can choose among permitted destinations.
  • Prefer application-relative URLs for internal navigation.
  • Avoid including sensitive information in redirect query strings.
  • Check authentication and authorization at the destination endpoint.
  • Call sendRedirect() before the response is committed.
  • Return immediately after redirecting so additional application logic does not accidentally run.
  • Use HTTPS for sensitive web applications.
  • Use the Post/Redirect/Get pattern after successful form processing when appropriate.
  • Use secure session management and invalidate sessions during logout.

19. Practical Mini Project: Student Registration Redirect

Build a small application in which students submit a registration form and are redirected to a confirmation servlet after validation.

Requirements

  • Create a registration form containing a student name and email address.
  • Submit the form using POST.
  • Validate the required fields on the server.
  • Return a 400 response if required data is missing.
  • Process or save valid registration data.
  • Redirect to a confirmation page after successful processing.
  • Display a clear confirmation message.

Sample Registration Form

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

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

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

Expected Workflow

  1. The student opens the registration form.
  2. The student enters registration details.
  3. The servlet validates the submitted values.
  4. The application processes the registration.
  5. The servlet redirects the browser to the confirmation endpoint.
  6. The confirmation page displays the result.

20. Best Practices for Maintainable Servlet Code

  • Keep servlet methods focused on handling HTTP requests and responses.
  • Move business logic into service classes.
  • Use a DAO or repository layer for database operations.
  • Keep URL mappings consistent across the application.
  • Use request.getContextPath() for redirects within the same application.
  • Handle errors before issuing the redirect.
  • Avoid printing response content before redirecting.
  • Use logging to diagnose redirect failures.
  • Test redirects under the actual application context path.
  • Choose forwarding, redirection, or direct response generation based on the application's requirements.

21. Practice Exercises

  1. Create a servlet that redirects users from /home to /welcome.
  2. Build a form that redirects to a success page after valid submission.
  3. Implement the Post/Redirect/Get pattern for a contact form.
  4. Create a login demonstration that redirects authenticated users to a dashboard.
  5. Redirect users to an external website using an absolute URL.
  6. Pass a non-sensitive status parameter through a redirect URL.
  7. Compare forwarding and redirection by implementing both approaches.
  8. Fix a redirect that fails when the application is deployed under a non-root context path.
  9. Implement an allowlist to prevent arbitrary external redirects.
  10. Test how the application behaves when the response has already been committed.

22. Interview Questions and Answers

Q1. What is sendRedirect() in Java Servlets?

Answer: It is a method of HttpServletResponse that sends a redirect response to the client and instructs it to make another request to a specified URL.

Q2. What is the default status code used by the traditional sendRedirect() method?

Answer: The traditional one-argument method uses HTTP 302 Found.

Q3. Does sendRedirect() create a new request?

Answer: Yes. The client normally sends a new HTTP request to the redirect destination.

Q4. What is the difference between sendRedirect() and forward()?

Answer: Redirection instructs the client to make a new request, while forwarding transfers processing to another server-side resource using the existing request.

Q5. Can sendRedirect() be used for external websites?

Answer: Yes. It can accept an absolute URL, provided the destination is appropriate and safe.

Q6. Why should getContextPath() be used in internal redirects?

Answer: It helps construct a URL that includes the web application's context path, making the redirect work when the application is deployed under different context paths.

Q7. What happens if sendRedirect() is called after the response is committed?

Answer: The Servlet API can throw an IllegalStateException because the response can no longer be redirected normally.

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

Answer: It is a pattern in which a successful POST request is followed by a redirect to a GET endpoint, helping prevent accidental resubmission when the result page is refreshed.

Q9. Are request attributes automatically preserved after redirection?

Answer: No. A redirect creates a new request, so request attributes from the original request are not automatically preserved.

Q10. How can session information remain available after a redirect?

Answer: Session information can remain available when the new request is associated with the same valid HTTP session.

Q11. What is an open-redirect vulnerability?

Answer: It occurs when an application redirects users to an untrusted destination supplied by an attacker, potentially enabling phishing or other attacks.

Q12. Can sendRedirect() pass form data to the next page automatically?

Answer: No. The new request does not automatically contain the original POST body. Use an appropriate server-side storage mechanism or a suitable application design if information must be preserved.

23. Quick Revision Checklist

  • sendRedirect() redirects the client to another URL.
  • The traditional one-argument method uses HTTP 302 Found.
  • The client normally sends a new HTTP request after receiving a redirect.
  • request.getContextPath() helps construct internal application URLs.
  • Redirection differs from server-side forwarding.
  • Request attributes and POST bodies are not automatically preserved.
  • The Post/Redirect/Get pattern is useful after successful form submissions.
  • Do not redirect to untrusted URLs without validation.
  • Call sendRedirect() before the response is committed.
  • Test redirect destinations and session behavior thoroughly.

24. Conclusion

The sendRedirect() method is an important part of Java Servlet development. It allows applications to navigate users between resources, redirect after successful form submissions, and guide users through authentication and application workflows.

Understanding the difference between redirection and forwarding, using context paths correctly, following the Post/Redirect/Get pattern, and validating redirect destinations will help you develop more reliable and secure Java web applications.

Continue learning Java Servlets and enterprise web development through the Advanced Java Training Course at JustAcademy.

To explore the training program, register for a course demo or visit the JustAcademy website.

Previous Next
whatsapp