I have a servlet with an overridden doGet method in a Dynamic Web App 3.0 targeted to GlassFish 3.1.
I’m studying for OCEJWCD exam and trying to memorize which circumstances throw which exceptions.
Due to Tomcat 6.0 only supporting Servlet 2.5 API, I have to use Glassfish 3 and I’m very confused with following situation.
Numerous old sources state that:
A response is committed as soon as the servlet starts to write
anything to the output stream. If you attempt a re-direct after the
response is committed you will receive an IllegalStateException error.
However Servlet 3.0 Final specification Section 5.3 states:
If data has been written to the response buffer, but not returned to
the client (i.e. the response is not committed), the data in the
response buffer must be cleared and replaced with the data set by
these methods. If the response is committed, these methods must throw
an IllegalStateException
What I want to know is, considering the PrintWriter.print() is committing the response, why don’t these lines throw IllegalStateException?
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String url = "http://someurl.com/";
PrintWriter out = response.getWriter();
out.print("This will be written into response buffer");
response.sendRedirect(url); // sendRedirect() after writing into buffer
}
I have to note that, I am able to fetch exceptions from GlassFish server log, I can clearly see that HttpServletRequest.getRequestDispatcher().forward(req,res); followed by a HttpServletResponse.sendRedirect(url); does indeed throw an IllegalStateException in GlassFish container.
The fact is that
PrintWriter.print()may commit the response. This happens if the buffer is full or if there’s no buffering at all. You can check its size by callingServletResponse.getBufferSize().ServletResponse.flushBuffer()orPrintWriter.flush()will definitely commit the response.So if
PrintWriter.print()was committing the response, then theHttpServletResponse.sendRedirect()would indeed throw anIllegalStateException.See also Servlet Specification, section 5.1 Buffering.
And btw., there’s no
RequestDispatcher.dispatch(). 😉