Java servlet not writing response bytes

后端 未结 2 759
天命终不由人
天命终不由人 2021-01-21 16:25

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

2条回答
  •  有刺的猬
    2021-01-21 16:38

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

    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();
    

    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...

提交回复
热议问题