当文档移动到新位置并且我们需要将客户端发送到该新位置时,通常使用页面重定向。这可能是由于负载平衡或简单的随机化。
将请求重定向到另一个页面的最简单方法是使用响应对象的sendRedirect()方法。以下是此方法的签名-
public void response.sendRedirect(String location) throws IOException
此方法将响应以及状态代码和新页面位置发送回浏览器。您还可以一起使用setStatus()和setHeader()方法来实现相同的重定向示例-
....
String site = "http://www.newpage.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
....此示例显示JSP如何执行页面重定向到另一个位置-
<%@ page import = "java.io.*,java.util.*" %>
<html>
<head>
<title>Page Redirection</title>
</head>
<body>
<center>
<h1>Page Redirection</h1>
</center>
<%
//要重定向的新位置
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。