I'm forwarding an action to from doFilter
method conditionally as the following code to another method :
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();
}
}
and my method that accepts the action and the response is that generates a jasper report file and sends it in the response :
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;
}
But no file is downloading and I get an exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
The problem was that I was firing Ajax request and I send the file to download in servlet response but the file to be download was handled by Ajax request in JavaScript on the success callback not the servlet response I handled the issue to send a direct URL to the file I want to download in the Ajax success call back and fire a new request to the that file specific URL.