I am having a program which picks a pdf file and let user download it. I do use OutputStream
for that and it works fine.
我有一个程序,它选择一个pdf文件,让用户下载它。我确实使用OutputStream,它工作正常。
However, on the same page, I want to display a text (on an actual website, for the user).
但是,在同一页面上,我想显示一个文本(在实际网站上,为用户)。
I have tried the PrintWriter
but that was in contrary with the OutputStream
, throwing an error saying I can't use them at the same time. So I decided to use ServletOutputStream's
print()
which didn't work. For some reason nothing was printed on the screen.
我尝试过PrintWriter,但这与OutputStream相反,抛出一个错误,说我不能同时使用它们。所以我决定使用ServletOutputStream的print(),它不起作用。出于某种原因,屏幕上没有打印出任何内容。
CODE:
File pdfFile = new File(filePath);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename="
+ "EloquaEmail.pdf");
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
// SOMEWHERE HERE I WOULD LIKE TO PRINT OUT THE TEXT (Some variable)
// I've tried:
// ServletOutputStream responseOutputStream = response.getOutputStream();
// PrintWriter responseOutputStream = response.getWriter();
// responseOutputStream.print(Main.htmlCode);
// responseOutputStream.close();
EDIT: Or would it be possible to open a new JSP page (besides the one with the save as dialog), passing the text variable? You know to simulate target=_blank
from within the servlet class?
编辑:或者是否可以打开一个新的JSP页面(除了带有另存为对话框的页面),传递文本变量?你知道从servlet类中模拟target = _blank吗?
I have tried this:
我试过这个:
String message = Main.htmlCode;
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("../WebContent/DownloadHtmlCode.jsp").forward(request, response);
Throws this error:
抛出此错误:
java.lang.IllegalStateException: Cannot forward after response has been committed
1 个解决方案
#1
You normally do that, by adding to your a jsp page which contains your text in meta tag:
您通常会这样做,通过添加到包含元标记中文本的jsp页面:
String message = Main.htmlCode;
response.setHeader("Refresh", "5;url=Display.jsp?message="+message);
#1
You normally do that, by adding to your a jsp page which contains your text in meta tag:
您通常会这样做,通过添加到包含元标记中文本的jsp页面:
String message = Main.htmlCode;
response.setHeader("Refresh", "5;url=Display.jsp?message="+message);