Java Servlet未写入响应字节 [英] Java servlet not writing response bytes

查看:52
本文介绍了Java Servlet未写入响应字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一些Java servlet(3.x-Tomcat 8),这些servlet生成并返回PDF文档.我从未遇到过任何问题.我最近写了一个新的servlet来创建和返回PDF文档,这个新的servlet使用的响应代码与其他代码使用的完全相同:完全相同:

I have a few Java servlets (3.x - Tomcat 8) running that generate and return PDF documents. I've never had any problems with any of them. I recently wrote a new servlet to also create and return a PDF document, and this new servlet is using the exact same piece of response code as the others are using:

response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\""+filename+".pdf\""); 
response.setContentLength(pdfBytes.length);

System.out.println("# Bytes => " + pdfBytes.length);

ServletOutputStream sos = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(sos);
bos.write(pdfBytes);
sos.flush();
sos.close();

就像我说的那样,这与其他方法一直很好,但是当我调用新的servlet时,即使上面的print语句具有非零值,它也返回0字节.

As I said, this has been working fine with the others, but when I call the new servlet, it returns 0 bytes, even though the print statement above has a non-zero value.

但是,如果我将上面的响应编写代码更改为:

However, if I change the response writing code above to:

OutputStream os = response.getOutputStream();
os.write(pdfBytes);
os.flush();
os.close();

...它工作正常,返回格式正确的PDF文档.为什么会发生这种情况?

...it works fine, returning a well-formed PDF document. Why might this be happening?

推荐答案

您没有刷新 BufferedOutputStream -因此它正在缓冲所有数据.您应该刷新那个,而不是 ServletOutputStream .

You're not flushing the BufferedOutputStream - so it's buffering all your data. You should flush that, not the ServletOutputStream.

但是,如果您只写一个字节数组,则无论如何都没有必要使用 BufferedOutputStream -而且您也不需要显式刷新,因为关闭会刷新.因此,您只需要:

However, if you're only writing a single byte array, there's no point in using BufferedOutputStream anyway - and you shouldn't need to explicitly flush anyway, as closing will flush. So you just need:

ServletOutputStream sos = response.getOutputStream();
sos.write(pdfBytes);
// Unclear whether *this* is needed, either.
sos.close();

我本人会期望 servlet容器来关闭输出流,但是从文档中尚不清楚.如果发生异常是否要关闭它是另一回事...

I'd personally expect the servlet container to close the output stream, but it's not clear from the docs. Whether you want to close it if an exception occurs is a different matter...

这篇关于Java Servlet未写入响应字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆