JSP - 页面重定向
在本章中,我们将讨论使用 JSP 进行页面重定向。页面重定向通常用于文档移动到新位置时,需要将客户端发送到该新位置。这可能是由于负载均衡,或者简单的随机化。
将请求重定向到另一页的最简单方法是使用 response 对象的 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。