Wednesday, June 18, 2008

IllegalStateException in a Servlet - when & why do we get?

Question: Why and when do we get IllegalStateException in a Servlet?

Answer: public class IllegalStateException extends RuntimeException - this runtime exception is thrown by a servlet to indicate that some requested operations have been called in an inappropriate state of the application or the environment. For example: If we try to write something on a response object which is already committed to the client then we'll get an IllegalStateException.

There are two common variants of this exception:-

  • Header Already Sent - java.lang.IllegalStateException: Header already sent - this exception is thrown we have already committed one or more headers to the client, so we can't set any headers anymore.
  • OutputStream or Writer Already Obtained -java.lang.IllegalStateException: Cannot forward as Output Stream or Writer has already been obtained - this exception is thrown if the servlet calls the forward() method after it has already obtained the Writer or the OutputStream associated with the response object by calling response.getWriter() or response.getOutputStream() methods respectively. That means the response has already been (or may have been) written and hence the response is not suitable for forwarding anymore.

How to avoid IllegalStateException in Servlets?

There may potentially be many reasons for this exception to occur, but we can follow the following guidelines to avoid it in most of cases:-
  • Don't use forward() once the Servlet has already used either response.getWriter() or response.getOutputStream()
  • Use a return statement immediately after using response.sendRedirect() method or requestDispatcher.forward() method to avoid writing to a response object which has already been committed to the client or in an inappropriate state.


No comments: