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>
      <%
         // New location to be redirected
         String site = new String("http://www.photofuntoos.com");
         response.setStatus(response.SC_MOVED_TEMPORARILY);
         response.setHeader("Location", site); 
      %>
   </body>
</html>

現在將上述程式碼放入 PageRedirect.jsp 並使用 URL https://:8080/PageRedirect.jsp 呼叫此 JSP。這會將你帶到給定的 URL http://www.photofuntoos.com

廣告