Consider the following code snippets. What will be displayed on the browser when a GET request is sent to FirstServlet assuming that the buffer is large enough to hold all the data before sending the data to the client?
In the doGet() of FirstServlet: PrintWriter out = response.getWriter(); out.println("<html><body>Page 1"); RequestDispatcher rd = request.getRequestDispatcher("NextServlet"); rd.forward(request, response); out.println("<br>Page 3</body></html>"); In the doGet() of SecondServlet: PrintWriter out = request.getWriter(); out.println("<br>Page 2");
Answer given: IllegalStateException at Runtime. Explanation given: The servlet specification mandates that when a request is "forwarded" to another resource, the buffer should be cleared of the contents generated by the forwarding resource. Therefore, only Page2 will be sent to the client. However, calling forward() means that the request processing is delegated to the callee resource permanently. So, although the control does return to the caller resource [because rd.forward() is just a regular method call], the caller resource cannot generate any output after the call to forward(). In this case, FirstServlet is trying to send output to the client after calling forward() and so an IllegalStateException will be thrown.
Is the given answer correct? From what I understand, anything written to the response stream after a request dispatch is ignored, and in fact, this example should output 'Page 2'. Page 1 won't be output because the buffer is cleared. Page 3 won't be output because anything written to the response after a request dispatch is ignored.
Well, being really pedantic - if in the code for the second servlet, the local variable request is of type HttpServletRequest (as the name suggests), then the code will never run (500 error because the second servlet won't compile; the method getWriter belongs to HttpServletResponse).
But that is, I guess, a red herring.
Otherwise, I agree with your assessment (and have tried it with Tomcat 5.5). "Page 2" is output, and any further attempt to write output on return to the first servlet is ignored (doesn't cause an exception).
You could get an IllegalStateException on the forward request itself - but only if the response in the first servlet had already been committed at the point where you called the forward request (SRV 8.4).
Joined: Apr 29, 2004
Oh yes - and if I had read the question more carefully, it explicitly rules out small buffer size being an issue (so in the absence of any other code, the response can't have been committed).