java.lang.IllegalStateException: STREAM錯誤的理解

我們在做文件上傳或者下載,或者過濾等操作時,可能要用到頁面的輸出流.
例如在JSP使用:
    response.reset();
    response.setContentType(”application/vnd.ms-excel”);
    OutputStream os = response.getOutputStream();  
拋出異常:
ERROR [Engine] StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
從網上找了下資料,綜合一下原因分析:
這是web容器生成的servlet代碼中有out.write(””),這個和JSP中調用的response.getOutputStream()產生衝突.
即Servlet規範說明,不能既調用 response.getOutputStream(),又調用response.getWriter(),無論先調用哪一個,在調用第二個時候應會拋出 IllegalStateException,因爲在jsp中,out變量是通過response.getWriter得到的,在程序中既用了response.getOutputStream,又用了out變量,故出現以上錯誤。
解決方案:
1.在程序中添加:
out.clear();
out = pageContext.pushBody();
就可以了;

2,不要在%][%之間寫內容包括空格和換行符
3,在頁面寫入圖片的時候,需要flush()
 OutputStream output=response.getOutputStream();
 output.flush();
4,在頁面確定寫入<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312”>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章