File 使用Servlet返回多个项目

File 使用Servlet返回多个项目,file,servlets,download,File,Servlets,Download,您好,我正在开发一个Servlet,它必须返回一个PDF文件和处理该文件的消息日志 到目前为止,我正在传递一个布尔值,根据用户选择,对其求值并返回日志或文件,如下所示: //If user Checked the Download PDF if (isDownload) { byte[] oContent = lel; response.setContentType("application/pdf");

您好,我正在开发一个Servlet,它必须返回一个PDF文件和处理该文件的消息日志

到目前为止,我正在传递一个布尔值,根据用户选择,对其求值并返回日志或文件,如下所示:

            //If user Checked the Download PDF
        if (isDownload) {
            byte[] oContent = lel;
            response.setContentType("application/pdf");
            response.addHeader("Content-disposition", "attachment;filename=test.pdf");
            out = response.getOutputStream();
            out.write(oContent);
        } //If user Unchecked Download PDF and only wants to see logs
        else {
            System.out.println("idCompany: "+company);
            System.out.println("code: "+code);
            System.out.println("date: "+dateValid);
            System.out.println("account: "+acct);
            System.out.println("documentType: "+type);

            String result = readFile("/home/gianksp/Desktop/Documentos/Logs/log.txt");
            System.setOut(System.out);

            // Get the printwriter object from response to write the required json object to the output stream      
            PrintWriter outl = response.getWriter();
            // Assuming your json object is **jsonObject**, perform the following, it will return your json object  
            outl.print(result);
            outl.flush();
        }
有没有一种有效的方法可以同时退回这两件物品


非常感谢

您可以将它们包装在DTO对象中,或者将它们放置在会话中以从JSP引用。

HTTP协议不允许您为每个HTTP请求发送多个HTTP响应。考虑到这一限制,您可以考虑以下备选方案:

  • 让客户端触发两个HTTP请求,例如,通过指定
    onclick
    事件处理程序,或者,如果您在第一个响应中返回HTML页面,则可以在
    窗口上触发另一个请求。加载
    页面。就绪
  • 为您提供一个机会,让您选择他想要下载的内容,并相应地在servlet中执行操作:如果他选择PDF,则返回PDF;如果他选择文本-返回文本,如果他选择两者-将它们打包到存档中并返回
  • 请注意,第一个变体既笨拙又不友好,就我而言,应该不惜一切代价避免使用。一个用户控制他得到什么的页面是一个更好的选择