Spring MVC with Jasper Report View

Sun, Nov 23, 2014

Java Programming #jasper report #java #spring

This article will demonstrate on how to integrate Jasper Report into Spring MVC. Jasper Report is a Java reporting library and with the help of iReport, we can design the report that tailored to our needs.

First we add an entry for Jasper Report into the pom.xml file.

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>5.5.0</version>
</dependency>

Then we add another entry into the mcv config file. Now you might have a different file name than I do, so the best is to refer to the configuration value in your web.xml file. Mine is something like this

<servlet>
    <servlet-name>systec-replacement</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>WEB-INF/spring/webmvc-config.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Therefore I will modify the webmvc-config.xml file and add a new bean entry

<bean id="helloReport"
class="org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView"
p:url="classpath:reports/helloreport.jasper" />

</beans>

And in the controller, create a method to display the report

@RequestMapping(value="/pdf", method = RequestMethod.GET)
public ModelAndView pdf(ModelAndView modelAndView) {
    logger.info("--------------generate PDF report----------");

    Map<String,Object> parameterMap = new HashMap<String,Object>();
    parameterMap.put("message", "Thor");
    //pdfReport bean has ben declared in the jasper-views.xml file
    modelAndView = new ModelAndView("helloReport", parameterMap);

    return modelAndView;
}

As we can see from the code above, the report is expecting a parameter name “message”, so we can now fire up the iReport program, create a new report and save as helloreport.jrxml. The extension is jrxml at the moment because we haven’t compile the report yet, once we compile iReport will produce a jasper file that we can use in the application. Since this is mainly to show how easy it is to integrate Jasper Report into Spring MVC, therefore I will only attach the screenshot of iReport about how the report is created.

Once we have the jasper file, we will place it into reports folder. When we fire a HTTP GET request to the pdf method, it will show something like below.