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.
I don’t think this works. I tried it and it didn’t work for me.
I seem to be having similar problems, and this solution does not solve it either…
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.
Thanks very much. The return worked for me.
Thanks it solved my problem!
Thanks. It worked for me as well. That had given me a bit of a headache!
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…
Thanks. The ‘return’ strategy works for me.