摘要:本文主要學習了請求轉發和響應重定向,以及二者之間的區別。html
使用HttpServletRequest對象的 getRequestDispatcher(String path) 方法獲取RequestDispatcher類型的轉發器。瀏覽器
使用RequestDispatcher轉發器的 forward(ServletRequest request, ServletResponse response) 方法進行轉發。服務器
1 @Override 2 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 3 req.getRequestDispatcher("/test.html").forward(req, resp); 4 }
使用HttpServletResponse對象的 sendRedirect(String location) 方法進行重定向到其餘資源。session
1 @Override 2 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 3 resp.sendRedirect("/HelloWorld/test.html"); 4 }
轉發只發送一次請求。ide
重定向發送兩次請求。學習
轉發地址欄沒有變化,執行刷新至關於從新發送信息到原頁面。spa
重定向地址欄有變化,執行刷新將發給新頁面。code
轉發能夠訪問WEB-INF下的資源。htm
重定向不能夠訪問WEB-INF下的資源。對象
轉發發生在服務器內部。
重定向發生在瀏覽器端。
轉發不能跳轉到本應用外的URL。
重定向能夠跳轉到任意URL。
經過 request.setAttribute(); 設置的屬性,若是讓下一個頁面訪問,只能經過轉發。
經過 session.setAttribute(); 設置的屬性,若是讓下一個頁面訪問,轉發和重定向均可以,建議使用轉發。