當須要將文檔移動到一個新的位置時,就須要使用JSP重定向了。html
最簡單的重定向方式就是使用response對象的sendRedirect()方法。這個方法的簽名以下:java
public void response.sendRedirect(String location) throws IOException
這個方法將狀態碼和新的頁面位置做爲響應發回給瀏覽器。您也能夠使用setStatus()和setHeader()方法來獲得一樣的效果:瀏覽器
.... String site = "http://www.runoob.com" ; response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); ....
這個例子代表了JSP如何進行頁面重定向:jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.io.*,java.util.*" %> <html> <html> <head> <title>頁面重定向</title> </head> <body> <h1>頁面重定向</h1> <% // 重定向到新地址 String site = new String("http://www.runoob.com"); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); %> </body> </html>
將以上代碼保存在PageRedirecting.jsp文件中,而後訪問http://localhost:8080/PageRedirect.jsp,它將會把您帶至http://www.runoob.com/。spa