Servlets 简明教程

Servlets - Page Redirection

页面重定向是一种将客户端发送到不同于请求的新位置的技术。当一个文档移到一个新位置或可能因为负载平衡时,通常使用页面重定向。

Page redirection is a technique where the client is sent to a new location other than requested. Page redirection is generally used when a document moves to a new location or may be because of load balancing.

将请求重定向到另一个页面的最简单方法是使用响应对象的 sendRedirect() 方法。以下是此方法的标志:

The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following is the signature of this method −

public void HttpServletResponse.sendRedirect(String location)
throws IOException

此方法会将响应连同状态代码和新页面位置一起发送回浏览器。您还可以同时使用 setStatus() 和 setHeader() 方法来实现相同的功能:

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

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

Example

此示例演示了 servlet 如何执行页面重定向到另一个位置:

This example shows how a servlet performs page redirection to another 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 {

      // Set response content type
      response.setContentType("text/html");

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

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

现在我们编译上述 servlet 并在 web.xml 中创建以下条目:

Now let us compile above servlet and create following entries in web.xml

....
<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>
....

现在,使用 URL [role="bare"] [role="bare"]http://localhost:8080/PageRedirect 调用此 servlet。这将重定向您到 URL [role="bare"] [role="bare"]http://www.photofuntoos.com

Now call this servlet using URL [role="bare"]http://localhost:8080/PageRedirect. This would redirect you to URL [role="bare"]http://www.photofuntoos.com.