[java] getOutputStream() has already been called for this response

I google the error message getOutputStream() has already been called for this response and many people said it is because of the space or newline after <% or %>, but in my code , there is no a space or a newline. I am using tomcat6 on linux.

<%@
    page import="java.servlet.*,
    javax.servlet.http.*,
    java.io.*,
    java.util.*,
    com.lowagie.text.pdf.*,
    com.lowagie.text.*"
    %><%
    response.setContentType("application/pdf");
    Document document = new Document();
    try{
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, buffer);
        document.open();
        PdfPTable table = new PdfPTable(2);
        table.addCell("1");
        table.addCell("2");
        table.addCell("3");
        table.addCell("4");
        table.addCell("5");
        table.addCell("6");
        document.add(table);
        document.close();
        DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
        byte[] bytes = buffer.toByteArray();
        response.setContentLength(bytes.length);
        for(int i = 0; i < bytes.length; i++)
        {
        dataOutput.writeByte(bytes[i]);
        }
    }catch(DocumentException e){
        e.printStackTrace();
    }

%>

~

org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:522)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:410)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

root cause

java.lang.IllegalStateException: getOutputStream() has already been called for this response
    org.apache.catalina.connector.Response.getWriter(Response.java:610)
    org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:198)
    org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
    org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
    org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:188)
    org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:118)
    org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:77)
    org.apache.jsp.Account.Domain.testPDF_jsp._jspService(testPDF_jsp.java:94)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

This question is related to java jsp tomcat

The answer is


Here is what worked for me in similar case.

After you finish writing into the Servlet OutputStream just call response.sendRedirect("yourPage.jsp");. That would cause initiation of a new request from the browser, therefore avoid writing into the same output stream.


JSP is s presentation framework, and is generally not supposed to contain any program logic in it. As skaffman suggested, use pure servlets, or any MVC web framework in order to achieve what you want.


I got the same problem, and I solved just adding "return;" at the end of the FileInputStream.

Here is my JSP

_x000D_
_x000D_
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"_x000D_
 pageEncoding="ISO-8859-1"%>_x000D_
<%@ page import="java.io.*"%>_x000D_
<%@ page trimDirectiveWhitespaces="true"%>_x000D_
_x000D_
<%_x000D_
_x000D_
 try {_x000D_
  FileInputStream ficheroInput = new FileInputStream("C:\\export_x_web.pdf");_x000D_
  int tamanoInput = ficheroInput.available();_x000D_
  byte[] datosPDF = new byte[tamanoInput];_x000D_
  ficheroInput.read(datosPDF, 0, tamanoInput);_x000D_
_x000D_
  response.setHeader("Content-disposition", "inline; filename=export_sise_web.pdf");_x000D_
  response.setContentType("application/pdf");_x000D_
  response.setContentLength(tamanoInput);_x000D_
  response.getOutputStream().write(datosPDF);_x000D_
_x000D_
  response.getOutputStream().flush();_x000D_
  response.getOutputStream().close();_x000D_
_x000D_
  ficheroInput.close();_x000D_
  return;_x000D_
_x000D_
 } catch (Exception e) {_x000D_
_x000D_
 }_x000D_
%>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


I had this problem only the second time I went to export. Once I added:

response.getOutputStream().flush();
response.getOutputStream().close();

after the export was done, my code started working all of the time.


Use Glassfish 4.0 instead. This turns out to be a problem only in Glassfish 4.1.1 release.

PT-BR: Use o Glasfish 4.0. Este parece ser um problema apenas no Glassfish 4.1.1.


Add the following inside the end of the try/catch to avoid the error that appears when the JSP engine flushes the response via getWriter()

out.clear(); // where out is a JspWriter
out = pageContext.pushBody();

As has been noted, this isn't best practice, but it avoids the errors in your logs.


I didn't use JSP but I had similar error when I was setting response to return JSON object by calling PrintWriter's flush() method or return statement. Previous answer i.e wrapping return-statement into a try-block worked kind of: the error disappeared because return-statement makes method to ignore all code below try-catch, specifically in my case, line redirectStrategy.sendRedirect(request, response, destination_addr_string) which seem to modify the already committed response that causes the error. The simpler solution in my case was just to remove the line and let client app to take care of the redirection.


In some cases this case occurs when you declare

Writer out=response.getWriter   

after declaring or using RequestDispatcher.

I encountered this similar problem while creating a simple LoginServlet, where I have defined Writer after declaring RequestDispatcher.

Try defining Writer class object before RequestDispatcher class.


This error was occuring in my program because the resultset was calling more columns to be displayed in the PDF Document than the database contained. For example, the table contains 30 fields but the program was calling 35 (resultset.getString(35))


The issue here is that your JSP is talking directly to the response OutputStream. This technically isn't forbidden, but it's very much not a good idea.

Specifically, you call response.getOutputStream() and write data to that. Later, when the JSP engine tries to flush the response, it fails because your code has already "claimed" the response. An application can either call getOutputStream or getWriter on any given response, it's not allowed to do both. JSP engines use getWriter, and so you cannot call getOutputStream.

You should be writing this code as a Servlet, not a JSP. JSPs are only really suitable for textual output as contained in the JSP. You can see that there's no actual text output in your JSP, it only contains java.


I got the same error by using response.getWriter() before a request.getRequestDispatcher(path).forward(request, response);. So start works fine when I replace it by response.getOutputStream()


I just experienced this problem.

The problem was caused by my controller method attempting return type of String (view name) when it exits. When the method would exit, a second response stream would be initiated.

Changing the controller method return type to void resolved the problem.

I hope this helps if anyone else experiences this problem.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to tomcat

Jersey stopped working with InjectionManagerFactory not found The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat Spring boot: Unable to start embedded Tomcat servlet container Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start Kill tomcat service running on any port, Windows Tomcat 8 is not able to handle get request with '|' in query parameters? 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE 403 Access Denied on Tomcat 8 Manager App without prompting for user/password Difference between Xms and Xmx and XX:MaxPermSize