有超过100份报告正在申请中。我想将它们集成到大型网络应用程序中。
我在这里找到了这个想法:http://jasperreports.sourceforge.net/sample.reference/webapp/index.html 。
所以,我想创建 Servlet,它将返回 pdf、html 或 xlsx 格式的报告。我已经通过 one Report 类的示例完成了此操作。此外,我的 servlet 返回从参数接收的类型。
但是,我无法实现为每个报告类编写(使用映射等)。 如何通过对不同的报告(不同的类)使用相同的 servlet 来避免这种情况。在本例中 - MyDataExample。
这里是:
public class ServletExample extends HttpServlet {
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
MyDataExample masterData = new MyDataExample(new ReportParameters(Long.valueOf(req.getParameter("id")), 2, DatabaseConnection.getConnection(), null));
JasperPrint print = masterData.build();
req.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, print);
String outputType = req.getParameter("outputType");
Exporter exporter;
switch (outputType) {
case "html":
try {
PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
req.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, print);
exporter = new HtmlExporter();
exporter.setExporterInput(new SimpleExporterInput(print));
SimpleHtmlExporterOutput output = new SimpleHtmlExporterOutput(out);
output.setImageHandler(new WebHtmlResourceHandler("/reports/image?image={0}"));
exporter.setExporterOutput(output);
exporter.exportReport();
} catch (JRException e) {
e.printStackTrace();
}
break;
case "pdf":
resp.setContentType("application/pdf");
exporter = new JRPdfExporter(DefaultJasperReportsContext.getInstance());
exporter.setExporterInput(new SimpleExporterInput(print));
try (OutputStream outputStreams = resp.getOutputStream()) {
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStreams));
exporter.exportReport();
} catch (JRException e) {
e.printStackTrace();
}
}
break;
case "xlsx":
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
exporter = new JRXlsxExporter(DefaultJasperReportsContext.getInstance());
exporter.setExporterInput(new SimpleExporterInput(print));
try (OutputStream outputStream = resp.getOutputStream()) {
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
configuration.setOnePagePerSheet(false);
configuration.setWhitePageBackground(false);
exporter.setConfiguration(configuration);
exporter.exportReport();
} catch (JRException e) {
e.printStackTrace();
}
break;
default:
throw new RuntimeException("Unknown type selected");
}
}
}
最佳答案
所以,我发现一切都很简单,只需刷新页面即可,因为你的浏览器可以缓存页面。 因此,您可以通过使用同一参数的不同值来获取不同的实例,例如:
if(req.getParameter("className").equals("A"))
classObject = new A();
else
classObject = new B();
这个示例非常完美,您也可以通过使用反射根据其名称创建类示例来自动执行此操作。
关于java - JasperReports Servlet 输出报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283392/