Monday, April 26, 2010

How to avoid IllegalStateException in java servlet?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

Example servlet source code snippet:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if("success".equals(processLogin())) {
response.sendRedirect("menu.jsp");
return; // <-- this return statement ensures that no content is adedd to the response further
}
Note: This same scenario of IllegalStateException is applicable in JSP also.

No comments: