方法一:response.sendRedirect("../success.jsp")
利用這個方法如果跳轉前有request.setAttribute("a","b")的話,那麼參數是傳不到success.jsp,因爲它在客戶端重定向到
success.jsp了,本質上跳了2次。所以參數失效,使用這個的時候會發現瀏覽器的URL地址發生了變化。
方法二:RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.jsp");
rd.forward(request,response);
利用這個方法跳轉,參數可以被正確傳送,而且效率比第一種高,IE的URL地址不變。
------------------------------------------------------------------------------------------------------
response.sendRedirect(response.encodeRedirectURL(request.getContextPath() +"/" +uri));
和
RequestDispatcher rd=servlet.getServletContext().getRequestDispatcher(uri);
rd.forward(request, response);
上面這兩種跳轉有什麼區別???
response.encodeRedirectURL(request.getContextPath() +"/" +uri));
這個是當使用session時,把session id符在uri的尾部一起傳送.當客戶關關cookie時使用.
所以你應該是在比較
response.sendRedirect(request.getContextPath() +"/" +uri)
及
RequestDispatcher rd=servlet.getServletContext().getRequestDispatcher(uri);
rd.forward(request, response);
的差別吧?
兩者最大的差別是下者把request及response的控制權帶到轉向的頁面.
------------------------------------------------------------------------------------------------------
還是個類似的問題:
我在表單提交時,比如提交到 http://localhost/myapp/reg.do 這個 action 裏;
在 action 裏處理完,跳轉到操作結果頁面,但是此時地址欄中還是顯示http://localhost/myapp/reg.do,刷新頁面,又提交一次
。
這樣的問題,用哪個跳轉能解決呢?
在http://localhost/myapp/reg.do的最後加入
response.sendRedirect("http://localhost/myapp/regResult.do");