Servlet Page Redirect

When a document is moved to a new location, we need to send this new location to the client, so we need to use page redirection. Of course, it may also be for load balancing, or just for simple randomization. Page redirection may be used in these cases.

The simplest way to redirect a request to another webpage 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 webpage location, back to the browser. You can also achieve the same effect by using the setStatus() and setHeader() methods together:

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

Example

This example shows how a Servlet redirects a page to another location:

package com.example.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
  {
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");

      // 要重定向的新位置
      String site = new String("http://www.example.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 call this Servlet by accessing the URL http://localhost:8080/PageRedirect. This will redirect you to the given URL http://www.example.com.

Other Extensions