出現java.lang.IllegalStateException的幾種情況
丟擲異常:
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();
就可以了;
我是在頁面輸出圖片之後寫的這兩句,程式碼如下:
//輸出圖象到頁面
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
2,不要在%][%之間寫內容包括空格和換行符
3,在頁面寫入圖片的時候,需要flush()
OutputStream output=response.getOutputStream();
output.flush();
4,在頁面確定寫入<meta http-equiv="Content-Type" content="text/html;charset=GB18030">
----------------------------------------------------------------------------------------------
在response.sendRedirect()時也可能會出現下列錯誤:
java.lang.IllegalStateException:
org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:423)
解決辦法如下:
在response.sendRedirect("");語句後面加上return語句就OK了。
例如:response.sendRedirect("");
return ;