Why do I get a "getOutputStream() has already been called for this response" error in JSP?

Tags: JSPOutputStreamiText 7

I'm using JDBC to fetch data from database and then I use iText to create a PDF file which can be downloaded on client machine. The application is coded in HTML/JSP and runs on Apache Tomcat.

I use the response.getOutputStream to create an output PDF file immediately. However, I get the following error:

getOutputStream() has already been called for this response

How can I generate a dynamic PDF file which can be downloaded by client machine?

Posted on StackOverflow on Jun 13, 2013 by Sahil Sharma

When you write JSP, you probably like white space and indentation, for instance:

<% //a line of code %>
<%
   // some more code
%>
<% // another line of code %>
<%
   response.getOutputStream();
%>

This will always cause the exception "getOutputStream() has already been called for this response" regardless if you're using iText or not. The getOutputStream() method was called the moment you introduced your first white space character in your JSP script.

To fix this, you need to remove all white space:

<% //a line of code %><%
   // some more code
%><% // another line of code %><%
   response.getOutputStream();
%>

Not a single character is accepted outside the <% and %> markers. As explained in the better JSP manuals, you shouldn't use JSP to create binary files. Why not? Because JSP introduces white space characters at arbitrary places in your binary file. That results in corrupt files. Use Servlets instead!

Click this link if you want to see how to answer this question in iText 5.