现在的位置: 首页 > 综合 > 正文

java.lang.IllegalStateException: getOutputStream() has already been call

2013年10月16日 ⁄ 综合 ⁄ 共 2315字 ⁄ 字号 评论关闭
java.lang.IllegalStateException: getOutputStream() has already been called for this response
 

在jsp向页面输出图片的时候,使用response.getOutputStream()会有这样的异常错误提示信息:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
的解决办法:
把所有%>和<%之间的空格、换行都删除掉

【原因】:
因为Application Server在处理编译jsp时对于%>和<%之间的内容通过PrintWriter输出(包括HTML标签,空格,回车等通过浏览器生成的标识符),而在上面的例子又要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制,
就会发生:getOutputStream() has already been called for this response的错误

 

例如:<%int i%>

<%int a%>应该写成:<%int i%><%int a%>这样的!!!!

 

 

是这个样子的,jsp都需要编译成servlet才能运行,本质上就是一个class,你可以在%Tomcat Home%/work/Catalina/localhost对应于你网站根路径的目录找到这个.java,你可以看到里面其实已经用了
PrintWriter out = response.getWriter();
或者类似的语句,这里面已经调用了一次getOutputStream().
所以如果你需要获得outputstream,一种方法就是你说的servlet,还有一种就是你可以直接引用out这个变量。不过这种做法只是一种投机的方法(万一在jsp编译出来的servlet变量名不是out就麻烦了),所以直接的方法还是servlet。
编写servlet不是很难,只要extends HttpServlet这个类,实现类中未实现的接口,在web.xml中加入url映射就行了,详细的可参考相关文档。直接用Myeclipse IDE或者JBuilder等IDE实现更简单,只要明白原理就不难。

 

在jsp向页面输出图片的时候,使用response.getOutputStream()会有这样的提示:

严重:   Servlet.service()     for     servlet     jsp     threw     exception  

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()放到循环体内

 

 

////////////////////////////////

第二种版本,我也是这么解决的:

解决:

由于jsp container在处理完成请求后会调用releasePageContet方法释放所用的PageContext object,并且同时调用getWriter方法,由于getWriter方法与在jsp页面中使用流相关的getOutputStream方法冲突,所以会造成这种异常,解决办法是:只需要在jsp页面的最后加上两条语句:  strong>out.clear();out=pageContext.pushBody();即可(其中out,pageContext均为jsp内置对象!)

抱歉!评论已关闭.