java.lang.IllegalStateException: getOutputStream() has already been called for this response 問題解決


我出現這種情況是在做一個下載功能的時候,下載成功就返回到某個頁面,然后就出現這錯誤。

這是

 

原因一:

  下載功能時,如果需要返回,系統默認把文件內容寫入到返回的地方,如果返回的地方沒有正確接收,則會報錯。不需要返回到某個頁面的時候,如果要跳轉,就跳轉到另一個控制器然后再跳轉到頁面就不會報錯。

原因二:
  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()放到循環體內




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM