Why Servlet request forwarding does not output write data from the source Servlet

Sun Weiqin"s "detailed explanation of Tomcat and Java Web Development Technology" (2nd edition) P149 request forwarding section has a problem that I don"t understand:

here is the code that implements CheckServlet to forward the request to OutputServlet. The confusion is that none of the data written by CheckServlet was sent to the client before and after the request was forwarded. Why?

(1) Source Servlet:

public class CheckServlet extends GenericServlet {

  public void service(ServletRequest request,ServletResponse response)
    throws ServletException, IOException {

    //
    
    request.setAttribute("msg", message);
 
    ServletContext context = getServletContext();
    RequestDispatcher dispatcher =context.getRequestDispatcher("/output");  
 
    PrintWriter out=response.getWriter();

    // Servletoutput
    out.println("Output from CheckServlet before forwarding request."); 
    System.out.println("Output from CheckServlet before forwarding request.");
    
    dispatcher.forward(request, response);

    // Servletoutput
    out.println("Output from CheckServlet after forwarding request."); 
    System.out.println("Output from CheckServlet after forwarding request.");
  }
}

(2) Target Servlet

public class OutputServlet extends GenericServlet {

  public void service(ServletRequest request,ServletResponse response)
    throws ServletException, IOException {

    String message = (String)request.getAttribute("msg");
    PrintWriter out=response.getWriter();

    out.println(message); 
    out.close();
  }
}
Sep.24,2021

well, the data written by the CheckServlet before and after the request forwarding should be sent to the client, but because the request is forwarded, all the display of the client side is generated by the forwarded servlet, and the client output generated by the pre-forwarded servlet will also be overwritten by the client output of the forwarded servlet. On the surface, it seems that the pre-forwarded servlet has no output.

Menu