转发对 struts 中另一个操作的响应并发送文件作为响应

forwarding response to another action in struts and sending file in response

我有条件地将一个操作从 doFilter 方法转发到另一个方法:

    public void dofilter(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
                              HttpServletResponse resp) {
    String reportType = request.getParameter("reportType");
    ActionForward actionForward = null;
    try {

       if (reportType.equals("completedChart")) {
                actionForward = cmsGetCompeltedTasks(mapping, actionForm,request, resp);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

我接受操作和响应的方法是生成一个 jasper 报告文件并在响应中发送它:

    public ActionForward cmsGetCompeltedTasks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {
            JasperReport jasperReport =                     fileName = COMPLETED_TASK + format.format(new Date()).toString() + ".xlsx";
                String filePath = servlet.getServletContext().getRealPath("") + fileName;
                System.out.println(filePath);
                JRXlsxExporter exporter = new JRXlsxExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, filePath);
                exporter.exportReport();                
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
                file = new File(filePath);
                FileInputStream fileInputStream = new FileInputStream(filePath);
                OutputStream responseOutputStream = response.getOutputStream();
                int bytes;
                while ((bytes = fileInputStream.read()) != -1) {
                    responseOutputStream.write(bytes);
                }
                responseOutputStream.flush();
                fileInputStream.close();
                 responseOutputStream.close();

        return mapping.findForward("cmsGetCompeltedTasks");


    } catch (Exception e) {
        e.printStackTrace();
    }           finally {
            file.delete();
        }

    return null;

}

但是没有文件正在下载,我得到一个异常:

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

您正在 servlet 中写入响应,您应该将其移动到 JSP

just don't write to the response in the servlet. That's the responsibility of the JSP.

将使用 response 的行移动到您重定向到

的 JSP
response.setContentType("application/vnd.openxmlformats- officedocument.spreadsheetml.sheet");
...

问题是我发出了 Ajax 请求,我在 servlet 响应中发送了要下载的文件,但是要下载的文件是由 JavaScript 中的 Ajax 请求处理的成功回调不是 servlet 响应 我处理了这个问题,直接 URL 发送到我想在 Ajax 成功回调中下载的文件,并向该文件特定 [=16] 发出新请求=].