JSP 页面重定向


当需要将文档移动到一个新的位置时,就需要使用JSP重定向了。

最简单的重定向方式就是使用response对象的sendRedirect()方法。这个方法的签名如下:

  1. public void response.sendRedirect(String location)
  2. throws IOException

这个方法将状态码和新的页面位置作为响应发回给浏览器。您也可以使用setStatus()和setHeader()方法来得到同样的效果:

  1. ....
  2. String site = "http://www.shouce.ren" ;
  3. response.setStatus(response.SC_MOVED_TEMPORARILY);
  4. response.setHeader("Location", site);
  5. ....

实例演示

这个例子表明了JSP如何进行页面重定向:

  1. <%@ page import="java.io.*,java.util.*" %>
  2. <html>
  3. <head>
  4. <title>Page Redirection</title>
  5. </head>
  6. <body>
  7. <center>
  8. <h1>Page Redirection</h1>
  9. </center>
  10. <%
  11. // 重定向到新地址
  12. String site = new String("http://www.shouce.ren");
  13. response.setStatus(response.SC_MOVED_TEMPORARILY);
  14. response.setHeader("Location", site);
  15. %>
  16. </body>
  17. </html>

将以上代码保存在PageRedirecting.jsp文件中,然后访问http://localhost:8080/PageRedirect.jsp,它将会把您带至http://www.shouce.ren/