java异常getOutputStream() has already been called for this response的原因和解决方法

来源:it942.com    发布时间:2008-11-13 11:22:46  浏览:

在Tomcat下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法,一般此问题出现在Linux系统下的Tomcat环境中。

在Tomcat下jsp中出现此错误一般都是在jsp中使用了输出流(如输出图片验证码,文件下载等)没有处理好的原因。
原因是在Tomcat中jsp编译成servlet之后在函数_jspService(HttpServletRequest request, HttpServletResponse response)的最后有一段这样的代码
finally {
       if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法和response.getOutputStream()冲突。所以会出现以上这个异常。

解决的办法其实很简单,在使用完输出流以后调用以下代码即可:
response.flushBuffer();
out.clear();
out = pageContext.pushBody();

下面是笔者提供的java下载文件代码:

  String filePath = request.getParameter("file");
  
  String sPath = request.getSession().getServletContext().getRealPath("/");  

  File dfile = new File(sPath+filePath);
        String fileName = dfile.getName();       

  response.setContentType("application/x-msdownload");
  response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

  ServletOutputStream sos = null;
  FileInputStream fis = null;
  
  try {
   
   sos = response.getOutputStream();
   fis = new FileInputStream(dfile);
   byte[] b = new byte[(int) dfile.length()];

   int i = 0;
   while ((i = fis.read(b)) > 0) {
    sos.write(b, 0, i);
   }

   sos.flush();
  } catch (Exception e) {
   
            System.out.println(e.toString());
           
        } finally {
         
            if (fis != null) {
                fis.close();
                fis = null;
            }
            if (sos != null) {
             sos.close();
             sos = null;
            }
            
   }