域对象 request
一)域对象:
1)request的生命周期:
从请求开始创建,到响应完成结束。
2) 作用:携带一次请求内的数据。
3)请求转发:
请求转发:
1)浏览器发送请求到服务器A,然后服务器A将请求转发到B 然后B处理结果将原路返回。二重定向,直接url发生变化,将客户端请求的直接转给另一个服务器。而不是由服务器A进行请求的转发。
2)服务器B可以获取浏览器的发送过来的所有参数。request可以进行属性值的设置类似servletcontex。而转发确不是,在服务器A设置的值 在B上无法获取。
方法:request.getRequestDispatcher("/req1").forward(request,response);
服务器A:
1 package jd.com.rsp; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 @WebServlet(name = "Servletreq") 11 public class Servletreq extends HttpServlet { 12 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 System.out.println("请求转发给req1"); 14 request.setAttribute("pwd","123"); 15 request.getRequestDispatcher("/req1").forward(request,response); 16 17 } 18 19 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 20 doPost(request,response); 21 } 22 }
服务器B:
1 package jd.com.rsp; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 10 @WebServlet(name = "Servletreq1") 11 public class Servletreq1 extends HttpServlet { 12 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 14 } 15 16 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 System.out.println("请求转发到req1了。"); 18 String user=request.getParameter("user"); 19 Object pwd=request.getAttribute("pwd"); 20 System.out.println("获取参数"+user); 21 System.out.println("获取req设置的值"+pwd); 22 } 23 }
学习是一种态度,坚持是质变的利器!