我有条件地将操作从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();
}
}
我接受操作和响应的方法是生成一个碧玉报告文件并将其发送给响应:
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
答案 0 :(得分:1)
您正在写servlet中的响应,应该将其移至JSP
只是不要在servlet中写入响应。这是JSP的责任。
使用response
将行移动到您重定向到的JSP
response.setContentType("application/vnd.openxmlformats- officedocument.spreadsheetml.sheet");
...
答案 1 :(得分:0)
问题是我触发了Ajax请求,并在Servlet响应中发送了要下载的文件,但要下载的文件是由JavaScript在成功回调上由Ajax请求处理的,而不是我处理该问题的Servlet响应来发送将URL指向要在Ajax成功调用中下载的文件,并向该文件特定的URL发出新请求。