I've been investigating the use of JasperReports (6.0.0) with Spring MVC (4.1.3) to generate PDF reports. Spring is rife with "Spring specific" ways to integrate with JasperReports to generate PDFs:
- Use
JasperReportsPdfView
relies on now deprecated JasperReport features - Use
JasperReportsMultiFormatView
- Use
JasperReportsViewResolver
I struggled to find good, complete examples online and wanted to share my findings (see my answer below).
Feel free to add additional methods and/or improvements related to "How can I integrate JasperReports with Spring4"?
Based on my research, I've found the following usage methods. The methods begin with the most direct (naive) approach involving less up front complexity / configuration and evolve to become more abstract but with more dependencies on Spring / more complex Spring configuration.
Method 1: Use the JasperReports API directly in the Controller
Just write out the content to the servlet output stream.
Method 2: Inject JasperReportPdf View into Controller
Given the JasperReportsPdfView bean:
This view can be injected or wired into the Controller for use:
Note that using the
JasperReportsPdfView
(or the more versatileJasperReportsMultiFormatView
) requires a dependency on spring-context-support:Method 3: Use XML or ResourceBundle view resolver to map logical view names to JasperReport views
Configure a new view resolver, in this case the
ResourceBundleViewResolver
to run before theInternalResourceViewResolver
. This is based on the order values being set (0 happens before 1):Then, at the root of our classpath, the
jasperreport-views.properties
file can contain the logical view name paired with the class and property values (i.e. url and reportDataKey) pertinent to rending a JasperReport:The controller code looks like this:
I like this approach. Controllers stay "dumb" and only deal with String values and the mapping of names to views can happen all in one location.
Method 4: Use JasperReportsViewResolver
Configure a zero-ordered
JasperReportViewResolver
and the trick is usesetViewNames
to tell Spring which logical view names you want this resolver to deal with (otherwise you end up with "Could not load JasperReports report from class path resource [jasperreports/index.jasper]" type errors):And inside the controller:
This is my preferred approach. Controllers resolve jasper reports in a very similar fashion to how jsp views are resolved using the
InternalResourceViewResolver
and there is therefore no need for an explicit mapping file as with the xml or properties file approach in method #3 above.EDIT
The javadocs for
JasperReportsPdfView
mention it uses the deprecatedJRExporter
API. Is there a better (newer) JasperReports view to use? Perhaps opting for theJasperReportsMultiFormatView
is a better option as it does not appear to useJRExporter
.