java.lang.IllegalStateException: getOutputStream() has already been called for this response

来源:互联网 发布:众海消防主机编程密码 编辑:程序博客网 时间:2024/06/06 03:44

最近查看apache tomcat日志,发现经常出现一个错误如下:

   严重: Servlet.service() for servlet jsp threw exception
   java.lang.IllegalStateException: getOutputStream() has already been called for this response

  网上查阅资料发现是response.getWriter()和response.getOutputStream()相冲突造成的,也就是getOutputStream()方法和getWriter()方法只能用一个。根据错误描述查看tomcat编译成的servlet文件时发现:在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();

 

原创粉丝点击