request 請求轉發:一種在服務器內部的資源跳轉方式
步驟:
1.通過request對象獲取請求轉發器對象:RequestDispatcher getRequestDispatcher(String path)
2.使用RequestDispatcher對象來進行轉發:forward(ServletRequest request, ServletResponse response)
特點:
1. 瀏覽器地址路徑不發生改變
2. 只能轉發到當前服務器內部資源中
3. 轉發是一次請求
request 共享數據(域對象)
* 域對象:一個有作用范圍的對象,可以在范圍內共享數據
* request域:代表一次請求的范圍,一般用於請求轉發的多個資源中共享數據
* 方法:
1. void setAttribute(String name,Object obj):存儲數據
2. Object getAttribute(String name):通過鍵獲取值
3. void removeAttribute(String name):通過鍵移除鍵值對
servletA:
1 @WebServlet("/RequestDemo8") 2 public class RequestDemo8 extends HttpServlet { 3 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 4 System.out.println("demo8............"); 5 //轉發到demo9 6 7 // RequestDispatcher requestDispatcher = request.getRequestDispatcher("/RequestDemo9"); 8 // requestDispatcher.forward(request,response); 9 10 //存儲數據到request域中 11 request.setAttribute("flypig","666"); 12 13 request.getRequestDispatcher("/RequestDemo9").forward(request,response); 14 } 15 16 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 //get獲取請求參數 18 19 //根據參數名稱獲取參數值 20 // String username = request.getParameter("username"); 21 // System.out.println("get"); 22 // System.out.println(username); 23 24 this.doPost(request,response); 25 } 26 }
servletB:
1 @WebServlet("/RequestDemo9") 2 public class RequestDemo9 extends HttpServlet { 3 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 4 5 //獲取數據, 6 Object attribute = request.getAttribute("flypig"); 7 //轉發資源時才能共享數據 8 System.out.println(attribute); 9 10 System.out.println("demo9..........."); 11 12 } 13 14 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 15 //get獲取請求參數 16 17 //根據參數名稱獲取參數值 18 // String username = request.getParameter("username"); 19 // System.out.println("get"); 20 // System.out.println(username); 21 22 this.doPost(request,response); 23 } 24 }