Upgrading from Tomcat 4.x to 5.0.19: java.lang.IllegalStateException

Seems like this new ‘feature’ of Tomcat 5 is buried in Google, bringing it to the top for anyone interested. If you port a servlet from Tomcat 4.x to Tomcat 5 and you use (pseudo) code like this:

public void doPost(HttpServletRequest req,HttpServletResponse res) {
   // some sort of logic
  if (something) {
   forward("/somewhere", req, res);
  } else {
   // do this
  }
   // continue on with the page
}

public void forward(String url, HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
  RequestDispatcher rd = req.getRequestDispatcher(url);
  rd.forward(req, res);
}

you’ll find that the servlet will throw a java.lang.IllegalStateException with the message: Cannot forward after response has been committed. This condition is easily fixed by adding a ‘return’ statement after you call the forward method. So instead, you’d have this:

  if (something) {
   forward("/somewhere", req, res);
   return;
  } else {
   // do this
  }
   // continue on with the page

I bet this one catches alot of people coming from a scripting background where it’s fine and dandy to do a response.redirect() (ASP) or a <cflocation> and then continue on as if nothing had happened.

Read it on jakarta.apache.org here.

8 thoughts on “Upgrading from Tomcat 4.x to 5.0.19: java.lang.IllegalStateException”

  1. I had this problem, and nothing was working for me. It turns out not to be solely a Tomcat issue. Check out this article for more info: http://java.oreilly.com/news/jsptips_1100.html It’s related to when the response buffer is flushed to the browser. Including/importing classes can force a flush, if it exceeds the buffer limit. After it flushes, you can’t send a redirect, or a forward…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>