當需要將文檔移動到一個新的位置時,就需要使用JSP重定向了。
最簡單的重定向方式就是使用response對象的sendRedirect()方法。這個方法的簽名如下:
public void response.sendRedirect(String location)
throws IOException
這個方法將狀態碼和新的頁面位置作為響應發回給瀏覽器。您也可以使用setStatus()和setHeader()方法來得到同樣的效果:
....
String site = "http://www.dabaquan.cn" ;
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.dabaquan.cn");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); %>
</body>
</html>
將以上代碼保存在PageRedirecting.jsp文件中,然后訪問http://localhost:8080/PageRedirect.jsp,它將會把您帶至http://www.dabaquan.cn/。