[code="java"]严重: Servlet.service() for servlet spring-mvc threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response[/code]
[code="java"]
严重: Servlet.service() for servlet spring-mvc threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:611)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:198)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:112)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:180)[/code]
尝试了网上和多的解决方案 无效!
下面的代码是在实现HTTP协议封装Response时的部分代码
SimpleHttpResponse.java
[code="java"]
OutputStream ops;
PrintWriter writer;
String ce = "utf-8";
public OutputStream getOutputStream() throws Exception {
if(dateType==W)throw new Exception("getWriter() has already been called!");
if(ops==null){
ops = new ByteArrayOutputStream();
dateType = O;
}
return ops;
}
public PrintWriter getWriter() throws Exception {
if(dateType==O)throw new Exception("getOutputStream() has already been called!");
if(writer==null){
ops = new ByteArrayOutputStream();
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(ops,ce)),true);
dateType = W;
}
return writer;
}
[/code]
W和O表示已经定义流的模式。
为什么getWriter()之后不能getOutputStream()?或者getOutputStream()之后不能getWriter()呢?
很简单writer是写入字符的,一行写完之后还可能会插入换行回车。显然是不能和outputStream重叠使用。
原理已经给出了,请楼主自己根据实际情况理解错误的原因。
请看看这个地址,也许对你有帮助。
http://www.189works.com/article-60271-1.html
[url]http://www.oschina.net/question/228356_71703[/url]
[url]http://stf-wlh.blog.hexun.com/8798148_d.html[/url]
原因:在JSP页面释放资源的时候,调用了ServetResponse.getWriter()方法
public java.io.PrintWriter getWriter()
Either this method or getOutputStream() may be called to write the body, not both
由于ServletResponse.getOutputStream()方法和该方法都有可能被调用,来输出JSP页面的内容,如果其中的一个方法被调用了,再调用另一个方法就会抛出异常。
在jsp页面最后加上:
out.clear();清空缓存的内容
out = pageContext.pushBody();
// ·返回一个新的BodyContent(代表一个HTML页面的BODY部分内容)
//·保存JspWriter实例的对象out
// ·更新PageContext的out属性的内容
流重复,不知道你是否是json数据的传递
OutputStream output = response.getOutputStream();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
output.flush();
out.clear();
out = pageContext.pushBody();
之前也遇到这个问题,就往excel中写数据,试了很多网上的解决方案,但是就是没解决掉,所以也就没解决了。总之对功能没影响,但是后台老是出现这个错误。期待哪位大侠能有什么好的解决方案出来。