Vodori’s Blog RSS Feed
 
 
 
 

Utilizing Jasper with Spring MVC

By: Ryan Fischer

Recently, I’ve had a project which was very heavy in the RIA department.  In some cases, the web page didn’t translate well for print friendly with the combination of the javascript and flash.  So I created a ‘print’ button to allow a pdf to be generated that showed the data that was present on the web.  I was able to use Spring MVC 2.5 in combination with Jasper Reports to product these reports.

The web portion of the app uses UrlBasedViewResolver in combination with the Tiles View and I needed a way for Spring to find the correct .jasper file and use the Jasper report view.  So I configed a second view resolver using the Resource Bundle View Resolver in the servlet.xml.  I provided basename with the value of views so that it would search in the classpath for the file view.properties.

    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">

        <property name="order" value="1"/>

        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
    </bean>
   <bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
        <property name="order" value="2"/>
        <property name="basename" value="views"/>

    </bean>

The view.properties file contains the mappings for the jasper file to be used, the view class to implement, and the name of the results that will be on the Model object.  I put the jasper files in the /WEB-INF/ folder to allow access on the web.


example.class=org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView
example.url=/WEB-INF/jasperreports/example.jrxml
example.reportDataKey=results

Using the very nice spring annotations I can write a simple method in a controller that grabs the list of results I would like to display in the report.  That list is used to create a JRBeanCollectionDataSource which is then put on the model.  Then all you have to do is return the string that maps back to the view.properties which would be “example.”   Spring will actually see if you have a tiles def with the name “example” first and then if it doesn’t find one it proceeds to the view.properties because of the order that was set prior in the servlet.xml.


@RequestMapping("/example/report.html")
public String generateExampleReport(ModelMap model){
List results = exampleService.getResults();

model.put(”results”, new JRBeanCollectionDataSource(results));

return “example”;
}

And there you have it, using Jasper with Spring MVC.

2 Responses to “Utilizing Jasper with Spring MVC”

  1. 1
    Rohit:

    Can you please share the code & supporting files for SpringMVC and Jasper. I am seeing Binding Exceptions. Thanks a lot for this article.

  2. 2
    Ryan:

    I can throw an example together later in the day and I will post it. What sort of binding exceptions are you seeing?

Leave a Reply