Spring MVC - JasperReports View

[Last Updated: Oct 1, 2017]

This example demonstrates how to use JasperReports Library in a Spring MVC application. JasperReports is a reporting engine. It takes input data coming from a data source (an implementation of Jasper's JRDataSource interface), fills the data source values into a user defined report template (an xml file with .jrxml extension) and then uses an exporter (an implementation of Jasper's JRExporter interface) to render resultant document in one of the variety of formats including HTML, PDF, Excel, OpenOffice and Word.


In this example, we will use the following Jasper components:

  • JRBeanCollectionDataSource It is an implementation of JRDataSource which is an Jasper abstraction of data source. This data source wraps a collection of JavaBean objects.

  • HtmlExporter It is an implementation of JRExporter interface which renders the report document in HTML format.

  • Jrxml file We will also need to write a jrxml file to define the report template.

Additional Maven Dependency



Above JasperReports dependency uses jackson-core 2.1.4. We need to exclude that because first of all we are not using any Jackson related feature in this example and secondly Spring expects Jackson's minimum version to be 2.5.0 for MappingJackson2HttpMessageConverter to work which is automatically initialized if the Jackson's ObjectMapper is on the classpath.

Java Config class

In this example, we are going to use BeanNameViewResolver for resolving the Jasper view. We will register an implementation of View as a bean and will return the bean name as a view name from the Spring controller. Check out this simple example of BeanNameViewResolver as well.

public class MyWebConfig {
  public ViewResolver beanNameViewResolver() {
      BeanNameViewResolver resolver = new BeanNameViewResolver();
      return resolver;

  public ViewResolver jspViewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      return viewResolver;

Implementing the View

Spring classes for JasperReport support are based on old deprecated Jasper API. We have to extend AbstractView to use the new JasperReport API directly.

package com.logicbig.example;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

public class CurrencyRateHtmlView extends AbstractView {
  private JasperReport currencyRatesReport;

  protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                         HttpServletResponse response) throws Exception {
      List<CurrencyRate> rates = (List<CurrencyRate>) model.get("todayCurrencyRates");
      //data source
      JRDataSource dataSource = getDataSource(rates);
      //compile jrxml template and get report
      JasperReport report = getReport();
      //fill the report with data source objects
      JasperPrint jasperPrint = JasperFillManager.fillReport(report, null, dataSource);
      //export to html
      HtmlExporter exporter = new HtmlExporter(DefaultJasperReportsContext.getInstance());
      exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
      exporter.setExporterOutput(new SimpleHtmlExporterOutput(response.getWriter()));

  private JRDataSource getDataSource(List<CurrencyRate> rates) {
      JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(rates);
      return dataSource;

  public JasperReport getReport() throws JRException {
      if (currencyRatesReport == null) {//compile only once lazily
          InputStream stream = getClass().getResourceAsStream("/rates.jrxml");
          currencyRatesReport = JasperCompileManager.compileReport(stream);
      return currencyRatesReport;
public class CurrencyRate {
  private String currencyPair;
  private Date date;
  private BigDecimal askPrice;
  private BigDecimal bidPrice;


<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns=""
              name="rates-template" pageWidth="595" pageHeight="842"
              columnWidth="555" leftMargin="20" rightMargin="20"
              topMargin="20" bottomMargin="20"

        <field name="currencyPair" class="java.lang.String"/>
        <field name="date" class="java.util.Date"/>
        <field name="askPrice" class="java.math.BigDecimal"/>
        <field name="bidPrice" class="java.math.BigDecimal"/>

        <band height = "50">
                <reportElement x = "0" y = "0" width = "120" height = "50" />
                <textElement verticalAlignment = "Middle">
                    <font size="16" isBold = "true" />
                <text><![CDATA[Currency Pair]]></text>
                <reportElement x = "120" y = "0" width = "120" height = "50" />
                <textElement verticalAlignment = "Middle">
                    <font size="16" isBold = "true" />
                <reportElement x = "240" y = "0" width = "120" height = "50" />
                <textElement verticalAlignment = "Middle">
                    <font size="16" isBold = "true" />
                <text><![CDATA[Ask Price]]></text>
                <reportElement x = "360" y = "0" width = "120" height = "50" />
                <textElement verticalAlignment = "Middle">
                    <font size="16" isBold = "true" />
                <text><![CDATA[Bid Price]]></text>

        <band height="25">
                <reportElement x="0" y="0" width="120" height="25"/>
                    <font size="14" />
                <textFieldExpression class="java.lang.String">
            <textField pattern="dd.MM.yyyy">
                <reportElement x="120" y="0" width="120" height="25"/>
                    <font size="14" />
                <textFieldExpression class="java.util.Date">
            <textField pattern="#,##0.00">
                <reportElement x="240" y="0" width="120" height="25"/>
                    <font size="14" />
                <textFieldExpression class="java.math.BigDecimal">
        <textField pattern="#,##0.00">
            <reportElement x="360" y="0" width="120" height="25"/>
                <font size="14" />
            <textFieldExpression class="java.math.BigDecimal">

Writing a Spring Controller

public class CurrencyRateController {

  public String mainView() {
      return "main";

  public String handleForexRequest(Model model) {
      model.addAttribute("todayCurrencyRates", getTodayForexRates());
      return "forexView";

  private List<CurrencyRate> getTodayForexRates() {
      //dummy rates
      List<CurrencyRate> currencyRates = new ArrayList<>();
      Date today = new Date();
      List<Currency> currencies = new ArrayList<>(Currency.getAvailableCurrencies());

      for (int i = 0; i < currencies.size(); i += 2) {
          String currencyPair = currencies.get(i) + "/" + currencies.get(i + 1);
          CurrencyRate cr = new CurrencyRate();
          BigDecimal bidPrice = new BigDecimal(Math.random() * 5 + 1);
          bidPrice = bidPrice.setScale(3, RoundingMode.CEILING);
          BigDecimal askPrice = new BigDecimal(bidPrice.doubleValue() + Math.random() * 2 + 0.5);
          askPrice = askPrice.setScale(3, RoundingMode.CEILING);

      return currencyRates;


<h2>Spring Jasper Report View Example</h2>
<a href="/exchangeRates">Get the today's Currency Rates</a>

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war


clicking on the link:

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 4.3.11.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • jasperreports 6.4.1: JasperReports Library.
  • JDK 1.8
  • Maven 3.3.9

Spring JasperReports View Example Select All Download
  • spring-jasper-view-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
          • resources
          • webapp
            • WEB-INF
              • views

    See Also