I am trying to open 开发者_StackOverflowa pdf file using ServletOutputStream
in JSP. The code is:
response.setContentLength(statementVO.getOutputStream().size());
response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
ServletOutputStream out = response.getOutputStream();
out.write(statementVO.getOutputStream().toByteArray());
out.flush();
out.close();
I am getting the following error
WAS 6.0 - Response already committed / OutputStream already obtained
You're getting this error because you're using a JSP file instead of a Java class to write Java code in. The JSP file is intented to serve template text like HTML/CSS/JS and so on. The JSP implicitly uses response.getWriter()
to write template text. Whenever you call response.getOutputStream()
inside a JSP, you risk getting this error because you cannot open both the Writer
and the OutputStream
. You can only open the one or the other, see also the linked javadocs.
To solve this problem there are basically 2 solutions:
Do this in a real Java class instead of a JSP file. A Servlet class is the best suitable place for this. You can find here a basic example.
Remove all template text (this includes whitespace and newlines!) from JSP file so that it doesn't implicitly call
response.getWriter()
. See also this answer for a detailed explanation.
if you want to send pdf file as response everytime, its better to use servlet instead of jsp. But if it's conditional state, you must send your response conditional! you can not write to response twice.
精彩评论