一、Servlet:
當(dāng)然,在servlet中,一般跳轉(zhuǎn)都發(fā)生在doGet, doPost等方法里面。
1) redirect 方式
response.sendRedirect("success.jsp");
頁面的路徑是相對路徑。sendRedirect可以將頁面跳轉(zhuǎn)到任何頁面,不一定局限于本web應(yīng)用中,如:
response.sendRedirect("http://www.ycul.com");
跳轉(zhuǎn)后瀏覽器地址欄變化。
這種方式要傳值出去的話,只能在url中帶parameter或者放在session中,無法使用request.setAttribute來傳遞。
2) forward方式
RequestDispatcher dispatcher = request.getRequestDispatcher("/a.jsp");
dispatcher .forward(request, response);
//跳轉(zhuǎn)到出口request.getRequestDispatcher("loginSuccess.jsp").forward(request, response);
頁面的路徑是相對路徑。forward方式只能跳轉(zhuǎn)到本web應(yīng)用中的頁面上。
跳轉(zhuǎn)后瀏覽器地址欄不會變化。
使用這種方式跳轉(zhuǎn),傳值可以使用三種方法: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)插入,頁面跳轉(zhuǎn)。
跳轉(zhuǎn)到Loginservler的doGet
二、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)
...
跳轉(zhuǎn)后瀏覽器地址欄變化
如果要跳到不同主機(jī)下,跳轉(zhuǎn)后,此語句后面的語句會繼續(xù)執(zhí)行,如同新開了線程,但是對response的操作已經(jīng)無意義了;
如果要跳到相同主機(jī)下,此語句后面的語句執(zhí)行完成后才會跳轉(zhuǎn);
2) response.setHeader("Location","");
此語句前不允許有out.flush(),如果有,頁面不會跳轉(zhuǎn)。
跳轉(zhuǎn)后瀏覽器地址欄變化
此語句后面的語句執(zhí)行完成后才會跳轉(zhuǎn)
3)
此語句前不允許有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)
...
跳轉(zhuǎn)后瀏覽器地址欄不變,但是只能跳到當(dāng)前主機(jī)下
此語句后面的語句執(zhí)行完成后才會跳轉(zhuǎn)