OutputStream already obtained

September 8, 2005

We stumbled over the following exception today:

java.lang.IllegalStateException: OutputStream already obtained
at com.ibm.ws.webcontainer.srt.SRTServletResponse.getWriter(SRTServletResponse.java:516)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:202)

which was caused by a Java Server Page that looked like this:


< %@ page contentType="text/html; charset=ISO-8859-1" % >
< %
response.getOutputStream().write("This is a test".getBytes());
response.getOutputStream().flush();
response.getOutputStream().close();
% >

This produces the following error:


This is a testError 500: OutputStream already obtained

The application server was IBM WebSphere 5.1.0. What made this error so strange is the fact that the JSP was already running successfully in production. The only change we made was cosmetical. It used to be:

< %@ page contentType="text/html; charset=ISO-8859-1" % >< %
response.getOutputStream().write("This is a test".getBytes());
response.getOutputStream().flush();
response.getOutputStream().close();
% >

(Please notice that there is no CR/LF in this code)

Which produces the expected:

This is a test

And yes, this JSP runs exception free. Why should the CR/LF make such a difference? In HTML and Server Pages you are usually allowed to make as many CR/LF as you want – it makes no difference.

Well, this one makes all the difference. Some googling told me that getOutputStream throws this Exception if getWriter() was called before. While we don’t call getWriter(), the CR/LF probably generates a line in the servlet that reads something like this:


response.getWriter().println("\r\n");

Even worse: The following doesn’t work properly, either:


< %@ page contentType="text/html; charset=ISO-8859-1" % >< %
response.getOutputStream().write("This is a test".getBytes());
response.getOutputStream().flush();
response.getOutputStream().close();
% >

(There are additional CR/LF at the end of the file)

Which produces:


This is a testError 500: OutputStream already obtained

There is no possibility to see this problem in the JSP. And that is highly annoying.

Of course Jakartas Tomcat runs both Server Pages without problem and that’s the way it should be. In Tomcat the writer is ignored and the OutputStream wins. This may produce wrong output, but at least you have the chance to find the bug…

Posted by Jerome Mueller

1 Comments

  1. Ritesh says:


    Hi dude…

    you saved my life…… i am so happy… great help… can’t say in words

    Thanks a lot

Leave a Reply