1. 程式人生 > >JSP三種頁面跳轉方式的比較

JSP三種頁面跳轉方式的比較

使用JSP大約有下列三種跳轉方式:
1. response.sendRedirect();
2. response.setHeader("Location","");
3. <jsp:forward page="" />

經過試驗得到下面的一些規則:

一. response.sendRedirect()

此語句前不允許有out.flush(),假如有,會有異常:
Java.lang.IllegalStateException: Can't sendRedirect() after data has committed to the client.
 at com.caucho.server.connection.AbstractHttpResponse.sendRedirect(AbstractHttpResponse.java:558)
...
跳轉後瀏覽器位址列變化
假如要跳到不同主機下,跳轉後,此語句後面的語句會繼續執行,如同新開了執行緒,但是對response的操作已無意義了;
假如要跳到相同主機下,此語句後面的語句執行完成後才會跳轉;
二. response.setHeader("Location","")

此語句前不允許有out.flush(),假如有,頁面不會跳轉。
跳轉後瀏覽器位址列變化
此語句後面的語句執行完成後才會跳轉
三. <jsp:forward page="" />

此語句前不允許有out.flush(),假如有,會有異常:
java.lang.IllegalStateException: forward() not allowed after buffer has committed.
 at com.caucho.server.webapp.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:134)
 at com.caucho.server.webapp.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:101)
 at com.caucho.jsp.PageContextImpl.forward(PageContextImpl.java:836)
 ...
跳轉後瀏覽器位址列不變,但是隻能跳到當前主機下
此語句後面的語句執行完成後才會跳轉