English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Web Page Redirect

When the document moves to a new location and we need to send this new location to the client, we need to use page redirection. Of course, it could also be for load balancing, or just for simple randomness, these situations are all possible to use page redirection.

The simplest way to redirect a request to another web page is to use the sendRedirect() method of the response object. Below 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 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.oldtoolbag.com";
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); 
....

Online Example

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

package com.w3codebox.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 the response content type
      response.setContentType("text/html;charset=UTF-8");
      // The new location to redirect to
      String site = new String("http://www.oldtoolbag.com");
      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 access the URL http://localhost:8080/PageRedirect to call this Servlet. This will redirect you to the given URL http://www.oldtoolbag.com.