利用RequestDispatcher对象进行请求转发,在这转发过程中的多个Servlet中打印它们的request对象和response对象,为什么request对象的地址全都不一样?而response对象的地址却全都相同?
不是说请求转发过程中,全程只有一次请求,对应一个request对象和一个response对象吗?
第一个Serrvlet的代码:
public class DispatcherServlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("-------------------------------------这里是Servlet1的doGet()-------------------------------");
System.out.println("Servlet1中的request:" + request);
System.out.println("Servlet1中的response:" + response);
// 获取请求转发的对象
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/dispatcher2");
// 走向请求转发的对象
requestDispatcher.forward(request,response);
// 业务流程走完,请求往回调,离开服务器时执行:
System.out.println("这里是Servlet1,此时所有的业务流程都已走完...");
}
}
第二个Servlet的代码:
public class DispatcherServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("-------------------------------------这里是Servlet2的doGet()-------------------------------");
System.out.println("Servlet2的request:" + request);
System.out.println("Servlet2中的response:" + response);
// 办理自己的业务
System.out.println("Servlet2 为请求办理相关业务...");
request.setAttribute("request",request);
//再一次转发
request.getRequestDispatcher("/dispatcher3").forward(request,response);
}
}
第三个Servlet的代码:
public class Dispatcher3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("--------------------------这里是Dispatcher3...-------------------------");
System.out.println("Servlet3中的request: " + request);
System.out.println("Servlet3中的response:" + response);
request.getRequestDispatcher("/WEB-INF/html/protectedForm.html").forward(request,response);
System.out.println("流程结束,页面返回....");
}
}
以上三个Servlet,从DispatcherServlet1 请求转发到 DispatcherServlet2 ,DispatcherServlet2 再次请求转发到Dispatcher3, 最后Dispatcher3 请求转发到 一个静态的html,结束整个过程返回结果。
以下是运行截图:
从运行结果可以看出,三个Servlet中的response对象地址都相同,符合预期。但三个request对象却各不相同,实在想不明白,希望能得到各位兄弟解答,感谢!