getOutputStream() has already been called for this response问题的解决

tomcat5下jsp出现getOutputStream() has already been called for this response异常的原因和解决方法

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

采用方法很简单.在使用OutputStream输出流完成后,调用下面2个方法即可解决该问题:
out.clear();
out = pageContext.pushBody();

示例代码:

OutputStream os=response.getOutputStream();
os.write(new String("true "+"nowNum=" + nowNum+"===").getBytes());
os.flush();
os.close();

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

还有以下方法

解决方法是捕获异常,代码如下:

java 代码

try {

............

} catch (RuntimeException e) {

e.printStackTrace();

}

如果还出现错误,可以用以下方法解决:

如果是在jsp页面,使用以下代码:


out.clear();

out=pageContext.pushBody();

//清除缓冲区中的内容,不将数据发送至客户端。

如果写成一个类的话,在产生验证码的方法里面,调用pageContext参数,在jsp里面,它是一个对象 ,因此在调用参数时加上类型Page(大写),引入的包为import javax.servlet.jsp.*(eclipse自带);

因此在java类里代码如下:

JspWriter out=page.getOut();//此处的out属于import javax.servlet.jsp.JspWriter方法的实例。

out.clear();

out=page.pushBody();

response.flushBuffer();

另外PageContex与ServletContext是不同的,PageContext就是JSP中的page,ServletContext就是JSP中的application,两者的scope不一样。

以上是我的一些想法,如有错误,欢迎回复交流。

<%@page import="java.util.*,
java.net.*,
java.text.*,
java.util.zip.*,
java.io.*"
%>

<%
request.setCharacterEncoding("GBK");
String filePath = request.getParameter("downfile");
String fileName = request.getParameter("filename");
System.out.println(filePath);
File f = new File(filePath);
System.out.println("filename:"+f.getName());
if (f.exists() && f.canRead()) {

response.setContentType("application/x-msdownload");
//response.setHeader("Content-Disposition", "attachment;filename=/"" + java.net.URLEncoder.encode(f.getName(),"UTF-8") + "/"");
response.setHeader("Content-Disposition", "attachment;filename=/"" + new String(f.getName().getBytes("GBK"),"iso8859-1") + "/"");

BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(f));
bos = new BufferedOutputStream(response.getOutputStream());

byte[] buff = new byte[2048];
int bytesRead;

while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}

} catch(final IOException e) {
System.out.println ( "IOException." + e );
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
bos.flush();
bos.close();
bos=null;
response.flushBuffer();
out.clear();
out = pageContext.pushBody();
return;
}
else
{
out.println("File Not Found!!!");
}
%>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值