1. 程式人生 > >getOutputStream() has already been called for this response 錯誤異常的處理

getOutputStream() has already been called for this response 錯誤異常的處理

  1.今天在做匯出excel匯出的專案中遇到了這個問題:


網上搜了一下,參考地址:http://www.cnblogs.com/jorton/archive/2012/05/04/2482609.html

原因是因為在匯出的時候使用response.getOutputStream() 和 response.getWriter()衝突。

2.解決方法

 在輸出流使用完後,加入下面兩端程式碼

 out.clear();

 out = pageContext.pushBody();

3.以下為參考原文:

  getOutputStream() has already been called for this response問題的解決
  在jsp向頁面輸出圖片的時候,使用response.getOutputStream()會有這樣的提示:java.lang.IllegalStateException:getOutputStream() has already been called for this response,會丟擲Exception

  原因一:
  JSP預設的輸出流為PrintWriter ,即<% %>以外的東西所預設的輸出方式,如果你嘗試在JSP中使用ServletOutputStream就會引起錯誤.要嘛直接改用Servlet輸出(複寫service方法),要嘛刪除除%><%中的任何東西(包括HTML標籤,空格,回車等東西)應該就可以。對於這樣的情況應該這樣來解決,刪除%><%之間的所有內容包括空格和換行符,最後也要消除空格和換行符,最好再加上一句response.reset()。
  原因二:    
  在J2EE的API參考裡有這麼個:

  ServletResponse的getWriter()方法裡會丟擲這個異常:

    IllegalStateException - if the getOutputStream method has already been called for this response object

  而它的getOutputStream()方法裡會丟擲這個異常:

    IllegalStateException - if the getOutputStream method has already been called for this response object

  並且兩者的函式申明裡都有這麼樣的一句
    Either this method or getOutputStream() may be called to write the body, not both.
    Either this method or getWriter() may be called to write the body, not both.


  以上說明也解釋了為什麼在往頁面中寫入圖片的時候要使用如下迴圈格式
  OutputStream output=response.getOutputStream();
  while((len=in.read(b)) >0) {
    output.write(b,0,len);
  }
output.flush();
而不是把response.getOutputStream().write()放到迴圈體內

在頁面中直接寫:
<body bgcolor="#ffffff">
<h1>
<%
response.getOutputStream();
%>
</h1>
</body>
將會出現錯誤訊息如下:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.catalina.connector.Response.getWriter(Response.java:604)
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)