Friday, February 22, 2013

Cannot call sendRedirect() after the response has been committed

So for the past few months I've noticed the following error on one page in our system: Cannot call sendRedirect() after the response has been committed
Nothing on that page that deals with the request or response has changed in the past few months and the error was only happening on my dev machine, our test and production servers worked fine, so I thought it was just my machine. The other day a colleague mentioned they were also getting the error. So we started looking into it. The java code in the page seemed fine, so for a while we were stumped. He realized that over the past few months lots of html code was put before the sendRedirect. So we moved the redirect to happen before the HTML code and our problem went away. Which reminded me, I've read somewhere that you can't have any HTML tags on a JSP page before the sendRedirect call because those tags are written to the response as they are hit, which effectively commits the response to that page making it impossible to forward to another page.

Lessons learned: Don't use a JSP page as a servlet or you will have weird bugs that only make sense when you view the generated code; don't forget HTML on a JSP commits the response.