Servlet頁面跳轉(zhuǎn)實現(xiàn)方法的區(qū)別
一直對Servlet頁面跳轉(zhuǎn)的幾種方式理解的糊里糊涂的,今天在網(wǎng)上搜了一把,找到一遍比較好的,記下來,以后看看。
Servlet頁面跳轉(zhuǎn)分兩部分,一是發(fā)生在Servlet,一是在JSP,其實JSP也就是servlet,不過還是有點差異滴。
Servlet:
當然,在servlet中,一般跳轉(zhuǎn)都發(fā)生在doGet, doPost等方法里面。
1) redirect 方式
response.sendRedirect("/a.jsp");
頁面的路徑是相對路徑。sendRedirect可以將頁面跳轉(zhuǎn)到任何頁面,不一定局限于本web應用中,如:
response.sendRedirect("URL");
跳轉(zhuǎn)后瀏覽器地址欄變化。
這種方式要傳值出去的話,只能在url中帶parameter或者放在session中,無法使用request.setAttribute來傳遞。
2) forward方式
RequestDispatcher dispatcher = request.getRequestDispatcher("/a.jsp");
dispatcher .forward(request, response);
Servlet頁面跳轉(zhuǎn)的路徑是相對路徑。forward方式只能跳轉(zhuǎn)到本web應用中的頁面上。
跳轉(zhuǎn)后瀏覽器地址欄不會變化。
使用這種方式跳轉(zhuǎn),傳值可以使用三種方法:url中帶parameter,session,request.setAttribute
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)后瀏覽器地址欄變化
如果Servlet頁面跳轉(zhuǎn)要跳到不同主機下,跳轉(zhuǎn)后,此語句后面的語句會繼續(xù)執(zhí)行,如同新開了線程,但是對response的操作已經(jīng)無意義了;
如果要跳Servlet頁面跳轉(zhuǎn)要到相同主機下,此語句后面的語句執(zhí)行完成后才會跳轉(zhuǎn);
2) response.setHeader("Location","");
此語句前不允許有out.flush(),如果有,頁面不會跳轉(zhuǎn)。
跳轉(zhuǎn)后瀏覽器地址欄變化
此語句后面的語句執(zhí)行完成后才會跳轉(zhuǎn)
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)
...
Servlet頁面跳轉(zhuǎn)后瀏覽器地址欄不變,但是只能跳到當前主機下
此語句后面的語句執(zhí)行完成后才會跳轉(zhuǎn)
【編輯推薦】