JSP - 页面重定向( Page Redirect)
在本章中,我们将讨论使用JSP重定向页面。 页面重定向通常在文档移动到新位置时使用,我们需要将客户端发送到此新位置。 这可能是因为负载平衡或简单的随机化。
将请求重定向到另一个页面的最简单方法是使用响应对象的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);
....
例子 (Example)
此示例显示JSP如何执行页面重定向到另一个位置 -
<%@ 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 。