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