`
xuepengcheng
  • 浏览: 46847 次
  • 性别: Icon_minigender_1
  • 来自: 郴州
社区版块
存档分类
最新评论

getOutputStream() has already been called for this

    博客分类:
  • JSP
阅读更多
今天早上用JSP写一个图片输出出现了这个异常,查了一下原因:

具体的原因就是
在tomcat中jsp编译成servlet之后在函数_jspService(HttpServletRequest request, HttpServletResponse response)的最后
有一段这样的代码
finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法是和
response.getOutputStream()相冲突的!所以会出现以上这个异常。

然后当然是要提出解决的办法,其实挺简单的(并不是和某些朋友说的那样--
将jsp内的所有空格和回车符号所有都删除掉),

在使用完输出流以后调用以下两行代码即可:
out.clear();
out = pageContext.pushBody();



<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<jsp:useBean id="DBO" scope="page" class="com.xue.bean.DBO" />
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'TestImageOut.jsp' starting page</title>
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>
 
  <body>
    This is my JSP page. <br>
    <%
       String sql="select image from My_Note where id=27";
       ResultSet rs=DBO.getResult(sql);
         while(rs.next())
       {
          ServletOutputStream sout=response.getOutputStream();
          InputStream in=rs.getBinaryStream(1);
         
          int len=0;
          byte b[]=new byte[2048];
          while((len=in.read(b,0,2048))!=-1)
          {
              sout.write(b);
          }
         
          sout.flush();
          sout.close();
          out.clear();
          out  =  pageContext.pushBody();
         
       }  
    %>
  </body>
</html>

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics