java.lang.IllegalStateException: getOutputStream() has already been called for this response

1.問題描述:html

  在平常練習的時候碰見的錯誤,雖然頁面能夠順利顯示,但後臺報錯:(雖然不影響導出效果,但看到後臺的異常,心裏仍是不舒服的)java

java.lang.IllegalStateException: getOutputStream() has already been called for this responseweb

從字義上分析:getOutputStream()已經調用了這個響應,就是重複被調用引發的異常。緩存

2.問題分析:tomcat

  在tomcat下jsp出現該錯誤通常都是在使用了輸出流(如輸出圖片驗證碼,文件下載等)。session

  產生這樣的異常緣由:是web容器生成的servlet代碼中有out.write(""),這個和JSP中調用的response.getOutputStream()產生衝突。即Servlet規範說明,不能既調用response.getOutputStream(),又調用response.getWriter(),不管先調用哪個,在調用第二個時候應會拋出IllegalStateException,由於在jsp中,out變量其實是經過response.getWriter獲得的,你的程序中既用了response.getOutputStream,又用了out變量,故出現以上錯誤。app

3.解決方案:jsp

  在調用 response.getOutputStream()以前,清空緩存的內容,並返回一個新的BodyContext,更新PageContext的out屬性的內容。this

 1 <body>
 2 <%
 3     BufferedImage imageBI=new BufferedImage(340,160,BufferedImage.TYPE_INT_RGB);
 4     Graphics g=imageBI.getGraphics();
 5      g.fillRect(0, 0, 400, 400);
 6      g.setColor(new Color(255,0,0));
 7      g.fillArc(20, 20, 100, 100, 30, 120);
 8      g.setColor(new Color(0,255,0));
 9      g.fillArc(20, 20, 100, 100, 150, 120);
10      g.setColor(new Color(0,0,255));
11      g.fillArc(20, 20, 100, 100, 270, 120);
12      g.setColor(new Color(0,0,0));
13      g.setFont(new Font("Arial Black",Font.PLAIN,16));
14      
15      g.drawString("red:climb",200,60);
16      g.drawString("green:swim", 200, 100);
17      g.drawString("blue:jump",200,140);
18      g.dispose();
19      out.clear();      //清空緩存的內容
20      out=pageContext.pushBody();  //更新PageContext的out屬性的內容
21      ImageIO.write(imageBI, "jpg", response.getOutputStream());
22 %>
23 </body>

 

 

4.擴展spa

  上面代碼,根本沒有用到out,爲何能夠調用out.clear和pageContext ? 由於這都是JSP的內置對象,能夠隨時使用。

  JSP九大內置對象(在JSP頁面上可直接使用,html頁面不能用):

  4.1 page:一個jsp就是一個servlet類,就是一個java類,java類的this對象,對應JSP的page對象;

  4.2 pageContext :當前頁對象

  4.3 application:上下文對象

  4.4 config :servlet生命週期 1.初始化

  4.5 request:請求。servlet生命週期 2.service方法:請求,響應

  4.6 response:響應

  4.7 session:請求對應session,有了request就能夠獲得session,session=request.getSession();

  4.8 out:response對應out對象--》這個就是這個異常根本所在;

  4.9 exception:異常對象(有代碼存在就會有異常存在)。

 

原文地址:http://www.javashuo.com/article/p-bamryuqi-ge.html

感謝大佬的文章

相關文章
相關標籤/搜索