javaservletsprintwriterforwardrequestdispatcher

Can we response to to the browser by a servlet before forwarding request to another servlet through forward method of RequestDispatcher class?


public class ForwardServlet extends HttpServlet {

    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.setAttribute("message","This message appended in ForwardServlet");
        resp.setContentType("text/html");
        PrintWriter pr = resp.getWriter();
        pr.println("I m in ForwardServlet"); //trying to response to the browser. but it is not executing, who block the PrintWriter (pr) object before calling forward method of RequestDispatcher ??
        
        RequestDispatcher rd= req.getRequestDispatcher("Servlet1");  
        rd.forward(req, resp);
        pr.println("Comeback to ForwardServlet from Servlet1"); //will not execute, because of either (1)control will not come back to this point??, or (2) PrintWriter (pr) object is blocked??
    }

}

To know executing mechanism


Solution

  • No, you can't do it with the same response object. The request dispatcher forwards uncommitted response to the new resurse and the browser doesn't know what is written to it until the response is committed by the new resource.

    This is what should you read about RewuestDispatcher::forward():

    Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response. For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.

    forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.