java后台写文件导出报错,找了很多文章都是在jsp中用内置对象out解决的,这里提供一种后台java解决办法
报错原因
是web容器生成的servlet代码中有out.write(""),这个和JSP中调用的response.getOutputStream()产生冲突。即Servlet规范说明,不能既调用response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出IllegalStateException,因为在jsp中,out变量实际上是通过response.getWriter得到的,你的程序中既用了response.getOutputStream,又用了out变量,故出现以上错误。虽然不影响导出,但是还是会报异常
jsp解决方式
在调用 response.getOutputStream()之前,清空缓存的内容,并返回一个新的BodyContext,更新PageContext的out属性的内容。
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "inline;filename="+fileName);
//在此处调用
out.clear();
out=pageContext.pushBody();
writeExcel(response.getOutputStream(),startDate,endDate);
java后台解决方式
将导出方法加个返回值,return null;
public Object export(ActivitiesSearchParam searchParam, HttpServletRequest request, HttpServletResponse response) throws Exception {
...
...
return null;
}