Stack: JSF + PrimeFaces on JBoss AS with 贾斯珀报告
我一直在使用 JasperReports 以 PDF 格式导出的模式,过程分为三个步骤:
[1] 从以下路径获取编译好的Jasper报告war
[2] 放置碧玉印刷会话中的对象
[3] 重定向到的 URLPDFServlet
因此,当用户从 GUI 单击p:命令按钮调用支持 bean 的方法,该方法会经历 [1]、[2] 和 [3],如以下示例代码所示:
xhtml 文件:
<p:commandButton ajax="false" action="#{indexController.exportPDF}" value="Export PDF"/>
支持 bean 代码:
private void putPrintObjectInSession() throws JRException {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
ServletContext context = (ServletContext) externalContext.getContext();
String reportFileName = context.getRealPath("/reports/PrimeNumbersReport.jasper");
File reportFile = new File(reportFileName);
if (!reportFile.exists())
throw new JRRuntimeException(".jasper file not found in the war.");
Map parameters = new HashMap();
parameters.put("ReportTitle", "2nd Prime Numbers Report");
parameters.put("BaseDir", reportFile.getParentFile());
JasperPrint jasperPrint =
JasperFillManager.fillReport(
reportFileName,
parameters,
getSQLConnection()
);
((HttpSession) externalContext.getSession(false)).setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
}
public String exportPDF() throws IOException, JRException {
putPrintObjectInSession();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.redirect("servlets/pdf");
return null;
}
我有两个问题:
[i] 您是否发现这种方法有任何明显的代码味道或限制?
[ii] 使用上面的示例代码,Chrome 和 Conkeror 都可以保存报告,但它们向用户提供的用于保存文件的默认文件名只是“pdf”。如何将其配置为有意义的名称(例如“report-2012-08-23c.pdf”)?