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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM