Servlet、JSP中頁面跳轉的方式


一、Servlet
當然,在servlet中,一般跳轉都發生在doGet, doPost等方法里面。
1)  redirect 方式
response.sendRedirect("success.jsp");
頁面的路徑是相對路徑。sendRedirect可以將頁面跳轉到任何頁面,不一定局限於本web應用中,如:
response.sendRedirect("http://www.ycul.com");
跳轉后瀏覽器地址欄變化。
這種方式要傳值出去的話,只能在url中帶parameter或者放在session中,無法使用request.setAttribute來傳遞。

2) forward方式
RequestDispatcher dispatcher = request.getRequestDispatcher("/a.jsp");
dispatcher .forward(request, response);

//跳轉到出口request.getRequestDispatcher("loginSuccess.jsp").forward(request, response);
頁面的路徑是相對路徑。forward方式只能跳轉到本web應用中的頁面上。
跳轉后瀏覽器地址欄不會變化。
使用這種方式跳轉,傳值可以使用三種方法:url中帶parameter,session,request.setAttribute
request.setAttribute("name",username);             (1)
 
String username=request.getParameter("username");  (2)
String pwd=request.getParameter("pwd");
System.out.println("用戶名:"+username+"密碼:"+pwd);


3)插入<a href=url></a>,頁面跳轉。
 <a href= "LoginUrl?username=guangchen&pwd=123456" >跳轉到Loginservler的doGet</a>
 
二、JSP
1)  response.sendRedirect();和servlet的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的操作已經無意義了;
如果要跳到相同主機下,此語句后面的語句執行完成后才會跳轉;


2)  response.setHeader("Location","");
此語句前不允許有out.flush(),如果有,頁面不會跳轉。
跳轉后瀏覽器地址欄變化
此語句后面的語句執行完成后才會跳轉

3)  <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)
...
跳轉后瀏覽器地址欄不變,但是只能跳到當前主機下
此語句后面的語句執行完成后才會跳轉


免責聲明!

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



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