JSP - 页面重定向

在本章中,我们将讨论使用JSP重定向页面.页面重定向通常在文档移动到新位置时使用,我们需要将客户端发送到此新位置.这可能是因为负载平衡或简单随机化.

将请求重定向到另一个页面的最简单方法是使用 sendRedirect()响应方法宾语.以下是此方法的签名 :

public void response.sendRedirect(String location)
throws IOException

此方法将响应以及状态代码和新页面位置发送回浏览器.您还可以同时使用 setStatus() setHeader()方法来实现相同的重定向示例 :

....
String site = "https://img01.yuandaxia.cn/Content/img/tutorials/jsp/www.newpage.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); 
....

示例

此示例显示JSP如何执行页面重定向到另一个location :

<%@ page import = "java.io.*,java.util.*" %>

<html>
   <head>
      <title>Page Redirection</title>
   </head>
   
   <body>
      <center>
         <h1>Page Redirection</h1>
      </center>
      <%
         // New location to be redirected
         String site = new String("http://www.photofuntoos.com");
         response.setStatus(response.SC_MOVED_TEMPORARILY);
         response.setHeader("Location", site); 
      %>
   </body>
</html>

现在让我们将上面的代码放在PageRedirect.jsp中,并使用URL http://localhost:8080/PageRedirect.jsp调用此JSP 的.这将带您到达给定的URL http://www.photofuntoos.com .