Search code examples
servletsspring-mvchttpresponseillegalstateexception

IllegalStateException:STREAM when calling response.getWriter


This is a method that's used for handle ajax request. So the output is written to the response

public ModelAndView myAction(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception
{
    //call other methods and send the response as arg
    //call getWriter on the response
}

According to this doc, I would definitely have an IllegalStateException if I call getWriter having already called getOutputStream(), so I suspect the methods I passed the response to did this although I don't really see them doing so... The only thing for sure is that at some point, one of the methods may do response.sendError(). Does this some how call getOutputStream()?


Solution

  • HttpServletResponse#sendError() commits the response and send an error status code. The javadoc states

    If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.

    In other words, after you call that method, the HTTP response has basically been sent. It makes no sense to call any of the getOutputStream() or getWriter() methods. Your Servlet container further makes it foolproof by throwing an Exception if you attempt to.