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.

This entry was posted in J2EE. Bookmark the permalink.

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

  1. Anonymous says:

    I don’t think this works. I tried it and it didn’t work for me.

  2. Rolf Mueller says:

    I seem to be having similar problems, and this solution does not solve it either…

  3. I too had the same problem and the solution of Aaron’s didn’t work — but, he provided the link to the issue (http://jakarta.apache.org/tomcat/faq/misc.html#illegalstate) and for me it wasn’t returns on “forward” commands, but on response.sendRedirect. That fixed my issue. Thanks Aaron.

  4. Terence says:

    Thanks very much. The return worked for me.

  5. Raj says:

    Thanks it solved my problem!

  6. bisola says:

    Thanks. It worked for me as well. That had given me a bit of a headache!

  7. Smito says:

    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…

  8. Daniel says:

    Thanks. The ‘return’ strategy works for me.

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>