如何将JasperReports与Spring MVC一起使用?

我一直在研究使用JasperReports(6.0.0)和Spring MVC(4.1.3)来生成PDF报告。Spring充满了“Spring特定”的方式,可以与JasperReports集成以生成PDF:

我努力在网上找到好的,完整的例子,并希望分享我的发现(见下面的答案)。

随意添加与“如何将JasperReports与Spring4集成”相关的其他方法和/或改进?


答案 1

根据我的研究,我发现了以下使用方法。这些方法从最直接(朴素)的方法开始,涉及较少的前期复杂性/配置,并演变为变得更加抽象,但更多地依赖于Spring /更复杂的Spring配置。

方法 1:直接在控制器中使用 JasperReports API

只需将内容写出到 servlet 输出流即可。

  @RequestMapping(value = "helloReport1", method = RequestMethod.GET)
  @ResponseBody
  public void getRpt1(HttpServletResponse response) throws JRException, IOException {
    InputStream jasperStream = this.getClass().getResourceAsStream("/jasperreports/HelloWorld1.jasper");
    Map<String,Object> params = new HashMap<>();
    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());

    response.setContentType("application/x-pdf");
    response.setHeader("Content-disposition", "inline; filename=helloWorldReport.pdf");

    final OutputStream outStream = response.getOutputStream();
    JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
  }

方法2:将JasperReportPdf视图注入控制器

给定 JasperReportsPdfView bean:

@Bean @Qualifier("helloWorldReport2")
public JasperReportsPdfView getHelloWorldReport() {
  JasperReportsPdfView v = new JasperReportsPdfView();
  v.setUrl("classpath:jasperreports/HelloWorld2.jasper");
  v.setReportDataKey("datasource");
  return v;
}

此视图可以注入或连接到控制器中,以供以下使用:

@Autowired @Qualifier("helloWorldReport2")
private JasperReportsPdfView helloReport;

@RequestMapping(value = "helloReport2", method = RequestMethod.GET)
public ModelAndView getRpt2(ModelAndView modelAndView) {
  Map<String, Object> parameterMap = new HashMap<>();
  parameterMap.put("datasource", new JREmptyDataSource());
  modelAndView = new ModelAndView(helloReport, parameterMap);
  return modelAndView;
}

请注意,使用(或更通用的)需要依赖弹簧上下文支持:JasperReportsPdfViewJasperReportsMultiFormatView

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>4.1.3</version>
</dependency>

方法 3:使用 XML 或 ResourceBundle 视图解析程序将逻辑视图名称映射到 JasperReport 视图

配置一个新的视图解析器,在本例中为 在 之前运行。这基于所设置的顺序值(0 发生在 1 之前):ResourceBundleViewResolverInternalResourceViewResolver

@Bean
public ResourceBundleViewResolver getResourceBundleViewResolver() {
  ResourceBundleViewResolver resolver = new ResourceBundleViewResolver();
  resolver.setBasename("jasperreport-views");
  resolver.setOrder(0);
  return resolver;
}

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/views/");
  resolver.setSuffix(".jsp");
  resolver.setOrder(1);
  return resolver;
}

然后,在我们的类路径的根目录中,该文件可以包含与与 rending JasperReport 相关的类和属性值(即 url 和 reportDataKey)配对的逻辑视图名称:jasperreport-views.properties

helloReport3.(class)=org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView
helloReport3.url=classpath:/jasperreports/HelloWorld3.jasper
helloReport3.reportDataKey=myDataSourceKey

控制器代码如下所示:

@RequestMapping(value = "helloReport3", method = RequestMethod.GET)
public ModelAndView getRpt3(ModelMap modelMap, ModelAndView modelAndView) {
  modelMap.put("myDataSourceKey", new JREmptyDataSource());
  return new ModelAndView("helloReport3", modelMap);
}

我喜欢这种方法。控制器保持“愚蠢”,只处理字符串值,并且名称到视图的映射可以在一个位置进行。


方法 4: 使用 JasperReportsViewResolver

配置一个零序,诀窍是告诉Spring你希望这个解析器处理哪个逻辑视图名称(否则你最终会得到“无法从类路径资源加载JasperReports报告[jasperreports/index.jasper]”类型错误):JasperReportViewResolversetViewNames

@Bean
public JasperReportsViewResolver getJasperReportsViewResolver() {
  JasperReportsViewResolver resolver = new JasperReportsViewResolver();
  resolver.setPrefix("classpath:/jasperreports/");
  resolver.setSuffix(".jasper");
  resolver.setReportDataKey("datasource");
  resolver.setViewNames("rpt_*");
  resolver.setViewClass(JasperReportsMultiFormatView.class);
  resolver.setOrder(0);
  return resolver;
}  

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/views/");
  resolver.setSuffix(".jsp");
  resolver.setOrder(1);
  return resolver;
}

控制器内部:

@RequestMapping(value = "helloReport4", method = RequestMethod.GET)
public ModelAndView getRpt4(ModelMap modelMap, ModelAndView modelAndView) {
  modelMap.put("datasource", getWidgets());
  modelMap.put("format", "pdf");
  modelAndView = new ModelAndView("rpt_HelloWorld", modelMap);
  return modelAndView;
}

这是我的首选方法。控制器解析 jasper 报告的方式与使用 jsp 视图解析的方式非常相似,因此不需要像上面方法 #3 中的 xml 或属性文件方法那样显式映射文件。InternalResourceViewResolver

编辑

Javadocs for JasperReportsPdfView提到它使用已弃用的API。有没有更好(更新)的JasperReports视图可以使用?也许选择JasperReportsMultiFormatView是一个更好的选择,因为它似乎没有使用。JRExporterJRExporter


答案 2

我的方法:

   @RequestMapping(value="getPDF", method=RequestMethod.GET)
   public void generatePDF(int idPredstave, HttpServletResponse response) throws Exception{

    Predstava p = pr.findById(idPredstave).get();
    List<Uloga> uloge = ur.findByPredstava(p);

    response.setContentType("text/html");
    JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(uloge);
    InputStream inputStream = this.getClass().getResourceAsStream("/jasperreports/Uloge.jrxml");
    JasperReport jasperReport = JasperCompileManager.compileReport(inputStream);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("nazivPredstave", p.getNaziv());
    params.put("trajanje", p.getTrajanje());
    params.put("opis", p.getOpis());
    params.put("zanr", p.getZanr().getNaziv());
    params.put("reziser", p.getReziser().getIme()+" "+p.getReziser().getPrezime());
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
    inputStream.close();


    response.setContentType("application/x-download");
    response.addHeader("Content-disposition", "attachment; filename=Uloge.pdf");
    OutputStream out = response.getOutputStream();
    JasperExportManager.exportReportToPdfStream(jasperPrint,out);
}

推荐