这是我第一次使用Jasper Report, 我需要使用Java Server Face JSF生成PDF,因此,在生成PDF后,它应该由浏览器下载
我使用netbeans代码生成的Web应用程序,使用java server faces framework和primefaces
public void createPDF() throws IOException {
List<Pelanggan> asdf = pelangganFacade.findAll();
try {
ServletContext ctx = (ServletContext)FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String ReportTemplate = ctx.getRealPath("/WEB-INF/Blank_A4.jasper");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("nama", asdf.get(1));
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance()
.getExternalContext().getContext();
response.addHeader("Content-disposition", "attachment; filename=testing.pdf");
ServletOutputStream outputStream = response.getOutputStream();
JasperPrint jasperPrint = JasperFillManager.fillReport(ReportTemplate, parameters);
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
outputStream.flush();
outputStream.close();
FacesContext.getCurrentInstance().responseComplete();
} catch (JRException ex) {
Logger.getLogger(TestReport.class.getName()).log(Level.SEVERE, null, ex);
}
}
但它不起作用并给我一个错误
java.lang.ClassCastException: org.apache.catalina.core.ApplicationContextFacade cannot be cast to javax.servlet.http.HttpServletResponse
Caused by: java.lang.ClassCastException: org.apache.catalina.core.ApplicationContextFacade cannot be cast to javax.servlet.http.HttpServletResponse
at com.joandilee.TestReport.createPDF(TestReport.java:55)
有没有简单的方法可以使用Jasper Report生成PDF报告,然后将其下载到浏览器?
答案 0 :(得分:1)
这不是贾斯珀错误 p>
替换
HttpServletResponse response = (HttpServletResponse)FacesContext
.getCurrentInstance().getExternalContext().getContext();
到
HttpServletResponse response = (HttpServletResponse) FacesContext
.getCurrentInstance().getExternalContext().getResponse();