Tuesday, May 26, 2009

java.lang.IllegalStateException: getOutputStream()

---------
Exception Trace
---------

java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.catalina.connector.Response.getWriter(Response.java:596)
org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:186)
org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:124)
org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:117)
org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:191)
org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:115)
org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
org.apache.jsp.SignalStreams_002dWebVolume_jsp._jspService(org.apache.jsp.SignalStreams_002dWebVolume_jsp:1008)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

--------
Solution
--------

Close the outputstream

--------
Sample
--------
I faced this problem while providing a excel file download functionality. It so happens that your first request might (if there has been a server restart) go right but in every subsequent requests this exception will occur. The most straight forward solution is to ensure that the output stream accessed has been closed properly.

an excerpt from a jsp ....


ServletOutputStream outs = null;
try
{
ServletOutputStream outs = response.getOutputStream();
response.setContentType("text/html");
response.setHeader("Content-Disposition",
"attachment; filename=\"myfile.xls\"");

... some code
... more functionality code

// Here we are trying to write file bytes to Outputstream
InputStream is = new FileInputStream("C:/myfile.xlsx");

int bit = 256;
int i = 0;

while ((bit) >= 0) {
bit = is.read();
outs.write(bit);
}
if(is!=null)
{
is.close();
}
}
catch(Exception e)
{}
finally{
if(outs != null) outs.close();
}

No comments:

Post a Comment