Servlet web page redirection


When the document is moved to a new location and we need to send the new location to the client, we need to use web page redirection. Of course, it may also be for load balancing, or just for simple randomness. In these cases, web page redirection may be used.

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

public void HttpServletResponse.sendRedirect(String location)
throws IOException

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

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

Example

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

import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PageRedirect extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置响应内容类型
      response.setContentType("text/html");

      // 要重定向的新位置
      String site = new String("http://www.w3cschool.cc");

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

Now let us 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>/PageRedirect</url-pattern>
 </servlet-mapping>
....

Now by accessing the URL http://localhost:8080/PageRedirect to call this Servlet. This will take you to the given URL http://www.w3cschool.cc.