入门servlet:request请求转发和共享数据
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 }