當(dāng)需要將文檔移動(dòng)到一個(gè)新的位置時(shí),就需要使用JSP重定向了。
最簡單的重定向方式就是使用response對(duì)象的sendRedirect()方法。這個(gè)方法的簽名如下:
public void response.sendRedirect(String location)
throws IOException
這個(gè)方法將狀態(tài)碼和新的頁面位置作為響應(yīng)發(fā)回給瀏覽器。您也可以使用setStatus()和setHeader()方法來得到同樣的效果:
....
String site = "http://www.soulsinkind.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
....
實(shí)例演示
這個(gè)例子表明了JSP如何進(jìn)行頁面重定向:
<%@ 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.soulsinkind.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); %>
</body>
</html>
將以上代碼保存在PageRedirecting.jsp文件中,然后訪問http://localhost:8080/PageRedirect.jsp,它將會(huì)把您帶至http://www.soulsinkind.com/。