Servlet Web Page Redirection

Web page redirection is a technique where one web page is made to redirect the user to another page. This is done for many reasons like moving your site to a new address, for load balancing or simply guiding the navigation flow within a web application.

In servlets, there are mainly two ways to redirect:

  1. Redirect response (HTTP status code 3xx): This tells the browser to make a new request to the provided URL.

  2. Request dispatcher: This is used to forward a request to another resource (like another servlet, JSP file, or HTML file) on the server. The browser doesn't know about this redirection because it's done completely on the server-side.

Here is an example of how you can do a redirection with a servlet:

Step 1: Create a new dynamic web project

Create a new dynamic web project in your IDE.

Step 2: Create a new Servlet

Create a new servlet in your project. We'll name it "RedirectServlet" for this tutorial.

Step 3: Write the Servlet code

In the created servlet, write the following code:

package com.example;

import java.io.IOException;

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

@WebServlet("/RedirectServlet")
public class RedirectServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

        // Get the destination from the request parameters
        String destination = request.getParameter("destination");

        if (destination != null) {
            if (destination.equals("google")) {
                response.sendRedirect("http://www.google.com");
            } else if (destination.equals("internal")) {
                request.getRequestDispatcher("/internalPage.html").forward(request, response);
            } else {
                response.getWriter().println("<h1>Unknown destination!</h1>");
            }
        } else {
            response.getWriter().println("<h1>No destination specified!</h1>");
        }
    }
}

In this servlet, we're getting a "destination" parameter from the request. If the destination is "google", we redirect the user to www.google.com using the sendRedirect method. If the destination is "internal", we forward the request to an internal page using the RequestDispatcher. If no destination is specified or if the destination is unknown, we send an error message.

Step 4: Running the Servlet

Run the servlet on your server.

You should now be able to see different results in response to different requests. For example, if the server is running on your local machine, you can access your servlet at http://localhost:8080/YourProjectName/RedirectServlet?destination=google to be redirected to www.google.com.

Note: The URL you pass to response.sendRedirect should be an absolute URL. If you pass a relative URL, the servlet container will turn it into an absolute URL for you, but this may not always give you the results you expect if your servlet is in a complex web application with a nested context path. The path you pass to request.getRequestDispatcher should be a path within your web application, not an absolute URL.

  1. Java Servlet redirect to another page: Redirecting involves sending an HTTP response to the client, instructing it to navigate to a different URL.

  2. Servlet sendRedirect method example: The sendRedirect method is used to redirect the client to a different URL.

    response.sendRedirect("newPage.jsp");
    
  3. Forwarding requests in Servlets: Forwarding allows the Servlet to internally forward the request to another resource.

    RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp");
    dispatcher.forward(request, response);
    
  4. Redirecting with query parameters in Servlet: Include query parameters in the redirect URL for passing data.

    response.sendRedirect("newPage.jsp?param=value");
    
  5. Servlet HTTP redirection status codes: Redirects typically use HTTP status codes like 302 (temporary redirect) or 303 (see other).

    response.setStatus(HttpServletResponse.SC_FOUND); // 302 Found
    
  6. Conditional redirection in Java Servlets: Use conditional statements to determine whether to perform a redirect.

    if (condition) {
        response.sendRedirect("newPage.jsp");
    }
    
  7. Redirecting to external URLs in Servlet: Redirecting to external URLs is possible by providing the full URL.

    response.sendRedirect("http://www.example.com");
    
  8. Redirecting after form submission in Servlet: Redirect after processing form data to avoid resubmission issues.

    response.sendRedirect("confirmationPage.jsp");
    
  9. Redirecting with JavaScript from Servlet: Include JavaScript code in the Servlet response to trigger client-side redirection.

    response.getWriter().println("<script>window.location.href='newPage.jsp';</script>");