如何打印文本,同时保存为'对话框显示在servlet中

时间:2015-05-04 12:42:54

标签: java servlets outputstream

我有一个程序可以选择一个pdf文件并让用户下载它。我确实使用OutputStream,它工作正常。

但是,在同一页面上,我想显示一个文本(在实际网站上,为用户)。

我尝试了PrintWriter,但这与OutputStream相反,抛出一条错误,说我无法同时使用它们。 所以我决定使用不起作用的ServletOutputStream's 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();

修改: 或者是否可以打开一个新的JSP页面(除了带有另存为对话框的页面),传递文本变量?你知道从servlet类中模拟target=_blank吗?

我试过这个:

String message = Main.htmlCode;
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("../WebContent/DownloadHtmlCode.jsp").forward(request, response);

引发此错误:

java.lang.IllegalStateException: Cannot forward after response has been committed

1 个答案:

答案 0 :(得分:0)

通常,您可以添加到包含元标记中文本的jsp页面:

 String message = Main.htmlCode;
 response.setHeader("Refresh", "5;url=Display.jsp?message="+message);