Originally posted by Neo Parker:
Hi,
I am practising Servlets. I am actually trying to generate the IllegalStateException, but in vain. This is what I am doing.
response.setContentType("text/html");
PrintWriter p = response.getWriter();
p.println("Hello11!!!");
response.setContentType("application/pdf");
p.println("Hello222!!!");
I am getting both the text displayed. Shouldn't this generate the exception. The same happens when I do sendRedirect after writing the response. The redirection works fine. No exception at all.
I am using Tomcat 5.0.28. Is the result vendor-dependent? Then in exam, if there is a question with the snippet like the one above, which option should we choose, an exception or proper output?.
Thanks in advance.
Howdy Neo !
1. Regarding 'public void setContentType(java.lang.String type)' :
It should not throw exception, not sure why do you think it should,
Please take a look here:
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletResponse.html 2. Regarding 'sendRedirect' : yes, it does throw java.lang.IllegalStateException
NOTE:if the response was *committed*, but if it is not, just imagine, some default buffer exists in servlet container implementation, then buffer contents just lost.
3. Servlet specification does *not* mandate any default buffer for HttpServletResponse, so if you see on the exam a question about sendRedirect behaviour after you wrote anything to writer -
you should select IllegalStateException answer and don't assume that any buffer will handle the situation.
NOTE:
JSP *does* have a default buffer which is defined in specification at size 8kb.
4. Tomcat servlet container has a HttpServletResponse implementation with a default buffer, so that's why you don't see exception during sendRedirect
test example.
5. To reproduce the *expected* behaviour, just add 'ServletResponse.flushBuffer' before calling 'sendRedirect'
You should get an exception in this case as written in
java docs.
5.a. As an alternative - you might try 'public void setBufferSize(int size)' before writing to writer.
regards,
MZ