請求轉發與重定向
阿新 • • 發佈:2020-08-07
請求的轉發
語法格式:
request.getRequestDispatcher(URL地址).forward(request, response);
實現程式碼:
1 public class OneServlet extends HttpServlet { 2 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 3 doGet(request, response);4 } 5 6 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 7 //請求轉發到index.jsp request.getRequestDispatcher("/index.jsp").forward(request,response); 8 } 9 }
重定向:
語法格式為:
response.sendRedirect(URL地址);
response.sendRedirect(request.getContextPath()+ URL地址);
實現程式碼:
1 public class OneServlet extends HttpServlet { 2 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 3 doGet(request, response); 4 } 5 6 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { 7 //重定向到index.jsp 8 response.sendRedirect("/index.jsp"); 9 } 10 }
轉發和重定向的區別:
請求轉發:
在伺服器內部完成,使用者感知不到,瀏覽器位址列不變,整個過程瀏覽器只發出了一個請求,目標資源可以在WEB-INF目錄下。
重定向:
伺服器以302狀態碼通知瀏覽器訪問新地址,瀏覽器位址列改變,整個過程瀏覽器發出兩次請求,目標資源不可以在WEB-INF目錄下。