项目踩坑之java.lang.IllegalStateException: getOutputStream() has already been called for this response

在做项目的时候,用到excel表格下载功能,虽然表格下载成功,但是控制台报如下错误
(java.lang.IllegalStateException: getOutputStream() has already been called for this response)

java.lang.IllegalStateException: getOutputStream() has already been called for this response
	at org.apache.catalina.connector.Response.getWriter(Response.java:607)
	at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:196)
	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:179)
	at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:116)
	at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:76)

导致的原因是:getOutputStream()方法和getWriter()方法冲突
然而在jsp页面上我只使用了getOutputStream()方法,哪来的getWriter()方法?

	response.setContentType("application/vnd.ms-excel");
	response.setHeader("Content-Disposition", "attachment;filename=ireport.xls");
	response.setContentLength(length);
	response.getOutputStream().write(reportContent, 0, length)
	response.flushBuffer();

在tomcat中jsp编译成servlet之后在函数_jspService(HttpServletRequest request, HttpServletResponse response)的最后
有一段这样的代码

finally {
       if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
     }

这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法是和
response.getOutputStream()相冲突的!所以会出现以上这个异常。
怎么解决呢?很好解决
在使用完输出流以后调用以下两行代码即可:

out.clear();
out = pageContext.pushBody();

改变之后的代码如下

	response.setContentType("application/vnd.ms-excel");
	response.setHeader("Content-Disposition", "attachment;filename=ireport.xls");
	response.setContentLength(length);
	response.getOutputStream().write(reportContent, 0, length)
	response.flushBuffer();
	out.clear();
	out = pageContext.pushBody();

这样就可以解决getOutputStream()方法和getWriter()方法冲突的报错了

你可能感兴趣的:(项目踩坑)