• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

IllegalStateException: getOutputStream() has already been called for this response

 
lavi mendonca
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
On my web page (Velocity), I have a link which when clicked opens a new page/ window (jsp). This page contains code to call my method in Java which accepts a request (HttpServeltRequest) and a response(HttpServletResponse) parameters, does some logic to generate a PDF file which is present in content byte array. And then sends it back to the browser via the response object.

Code in Java Class below:

public synchronized void processRequest(HttpServletRequest request, HttpServletResponse response) {

...... some code......
.................
.................
content = renderXML(xmlContent, xslTemplate);
if (content != null) {
//Send the result back to the client
response.setContentType("application/pdf");
response.setContentLength(content.length);
response.getOutputStream().write(content);
response.getOutputStream().flush();
}
}

But it throws the exception �
org.apache.jasper.JasperException: getOutputStream() has already been called for this response
----- Root Cause -----java.lang.IllegalStateException: getOutputStream() has already been called for this response at org.apache.coyote.tomcat4.CoyoteResponse.getWriter(CoyoteResponse.java:552)

Any idea how to get around this problem?? I require the solution immediately. I also tried the below code and got the same exception.

OutputStream os = response.getOutputStream();
os.write(content);
os.flush();

Interestingly the pdf gets displayed in the browser with both the codes. But the exception is thrown as well. Also, the original JSP Page is displayed as a blank page.. I need to close that window when the PDF is displayed.

Any help would be appreciated.
Thanks in advance.
 
Stefan Evans
Bartender
Posts: 1780
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basic rule of HTTP: one request, one response.

You can only send back one thing to a request.
Either an HTML page, or a PDF document, or an image or....
Specifically you can't send an HTML page AND a PDF document.
Java complains if you have already obtained a writer/outputstream as you should only be getting ONE of these.

JSPs by default send back text, and so obtain the writer for themselves.
If you are sending back a PDF, and trying to get the output stream, obviously it raises a conflict of interest.

Solution - use a servlet rather than a JSP to call your PDF code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic