JSP页面重定向

以下内容引用自http://wiki.jikexueyuan.com/project/jsp/page-redirect.html

页面重定向通常用于当一个文件移动到一个新的位置,需要向客户端发送到这个新的位置,或可能是因为负载平衡,或简单随机化。

请求重定向到另一个页面的最简单的方法是使用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>
<%
   // New location to be redirected
   String site = new String("http://www.easonjim.com");
   response.setStatus(response.SC_MOVED_TEMPORARILY);
   response.setHeader("Location", site); 
%>
</body>
</html>

现在将上面的代码放在PageRedirect.jsp中,并且使用URL:http://localhost:8080/PageRedirect.jsp来调用此JSP。它将跳转到页面http://www.easonjim.com。

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/jspbasics/test13

posted @ 2017-06-07 02:14  EasonJim  阅读(2088)  评论(0编辑  收藏  举报