August 2, 2009

Servlet: getWriter() has already been called for this response

Topic:  Servlets 2.4

Application Server: JBoss 4.0.2 / Tomcat 5.5.9

Exception:

java.lang.IllegalStateException: getWriter() has already been called for this response
 org.apache.catalina.connector.Response.getOutputStream(Response.java:565)
 org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:171)
 com.HelloWorldServlet.doGet(HelloWorldServlet.java:31)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:697)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
 org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)

Resolution:

The output to the response can be either done with the PrintWriter object procured from the respone.getWriter() method or with the ServletOutputStream object procured from the response.getOutputStream() method, but not both, in the Servlet.

If the getWriter() is already called on the response object, the call to getOutputStream() on the same response object will theow an IllegelStateException and vice versa.

1 comment: