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();
}
}