Easy Tutorial
❮ Servlet Exception Handling Servlet File Uploading ❯

Servlet Web Page Redirection

When a document is moved to a new location, we need to send this new location to the client. Web page redirection is also used for load balancing or simply for random purposes.

The simplest way to redirect a request to another web page is by using the sendRedirect() method of the response object. Here is the definition of this method:

public void HttpServletResponse.sendRedirect(String location)
throws IOException

This method sends the response along with the status code and the new web page location back to the browser. You can also achieve the same effect by using the setStatus() and setHeader() methods together:

....
String site = "http://www.tutorialpro.org" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); 
....

Example

This example demonstrates how a Servlet can redirect a page to another location:

package com.tutorialpro.test;

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;

/**
 * Servlet implementation class PageRedirect
 */
@WebServlet("/PageRedirect")
public class PageRedirect extends HttpServlet{

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html;charset=UTF-8");

      // New location to be redirected
      String site = new String("http://www.tutorialpro.org");

      response.setStatus(response.SC_MOVED_TEMPORARILY);
      response.setHeader("Location", site);    
    }
}

Now, let's compile the above Servlet and create the following entry in the web.xml file:

....
 <servlet>
     <servlet-name>PageRedirect</servlet-name>
     <servlet-class>PageRedirect</servlet-class>
 </servlet>

 <servlet-mapping>
     <servlet-name>PageRedirect</servlet-name>
     <url-pattern>/TomcatTest/PageRedirect</url-pattern>
 </servlet-mapping>
....

Now, call this Servlet by accessing the URL http://localhost:8080/PageRedirect. This will redirect you to the given URL http://www.tutorialpro.org.

❮ Servlet Exception Handling Servlet File Uploading ❯