Sunday, December 19, 2010

Spring 3 MVC - DynamicJasper Integration Tutorial

In this tutorial we will integrate DynamicJasper with a simple Spring 3 MVC application. We will provide a custom data source where DynamicJasper will retrieve its data. The application will be layered so that we can easily modify the features or implementations of our application.

What is DynamicJasper?
DynamicJasper (DJ) is an open source free library that hides the complexity of Jasper Reports, it helps developers to save time when designing simple/medium complexity reports generating the layout of the report elements automatically.


What is JasperReports?
JasperReports is the world's most popular open source reporting engine. It is entirely written in Java and it is able to use data coming from any kind of data source and produce pixel-perfect documents that can be viewed, printed or exported in a variety of document formats including HTML, PDF, Excel, OpenOffice and Word.


Similar with our previous tutorial. We will setup our Spring 3 MVC application first. If you need a review with Spring MVC, I suggest you read the other tutorials I've posted. Or you can also Google for related tutorials.

Here's a screenshot of the report document that we will be generating:

This is just basic. You can add and show more features with Jasper and DynamicJasper. For now, we'll stick with the basics.

Our first task is to setup the main controller that will handle the download request.


This controller declares two mappings:
/download - for showing the download page
/download/xls - for retrieving the actual Excel report

Examine the doSalesReportXLS() controller method. It has a reference to a download service named downloadService. This service handles the actual report processing. Later, we'll discuss that in-depth.

The /download mapping will display the downloadpage view which resolves to /WEB-INF/jsp/downloadpage.jsp


This is a simple JSP. It has an HTML link for downloading the report. Notice the URL points to /krams/main/download/xls. The same mapping we have in the MainController.

Here's a screenshot of this page:

Next, we enable Spring MVC in the web.xml


Take note of the URL pattern. When accessing any pages in our MVC application, the host name must be appended with

In the web.xml we declared a servlet-name spring. By convention, we must declare a spring-servlet.xml as well.


This XML config declares a view resolver. All references to a JSP name in the controllers will map to a corresponding JSP in the /WEB-INF/jsp location.

By convention, we must declare an applicationContext.xml


This XML config declares three beans to activate the Spring 3 MVC programming model.

Let's return back to DynamicJasper.

If you remember back in the MainController we declared a reference to a DownloadService which is automatically injected by Spring.

The DownloadService is a delegate. All reporting processing is handled by this service.


To generate the report, we call the downloadXLS() method. This generates an Excel report. Let's examine further how the report is generated:

1. Retrieve an instance of our datasource:
SalesDAO datasource = new SalesDAO();
JRDataSource ds = datasource.getDataSource();

The datasource can come from a variety of sources like from an in-memory list, database, and alike. Later, we'll show what's inside this SalesDAO

2. Generate the Jasper layout:
ReportLayout layout = new ReportLayout();
DynamicReport dr = layout.buildReportLayout();

The layout is like the template of your report. It's basically the design of how you want the report to look like. Our Jasper layout is actually generated on the fly by DynamicJasper. That's the main purpose of DynamicJasper. It will dynamically, programmatically generate the layout. This is useful for generating tabular reports which are mostly used for professional applications. If you need to manually design or create an artistic layout, I advise you try layouting using Jasper's native JRXML format. DynamicJasper can also use a JRXML template, but that's beyond the scope of this tutorial.

3. Compile the Jasper layout into a JasperReport object:
JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, new ClassicLayoutManager(), params);

The JasperReport object is the compiled version of your layout that can be understood by Jasper. Imagine it like this: the layout is for humans, while the compiled object is for the computer.

4. Create the Jasper print:
JasperPrint jp = JasperFillManager.fillReport(jr, params, ds);

This basically fills the JasperReport with contents from the datasource.

5. Export the report to your desired format. For this tutorial we will export it as an
Excel document.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Exporter exporter = new Exporter();
exporter.export(jp, baos);

Here we pass an instance of a ByteArrayOutputStream and a JasperPrint object.

6. Set the response header and content type:
String fileName = "SalesReport.xls";
response.setHeader("Content-Disposition", "inline; filename="+ fileName);

Make sure you set the correct contentType.

7. Write the report to the output stream:
writeReportToResponseStream(response, baos);

Now, let's examine the remaining classes.

The ReportLayout
This is a custom wrapper to DynamicJasper's FastReportBuilder. The purpose of this class is to encapsulate the layout of the report. This isn't mandatory. You can remove the contents of buildReportLayout() and place it along with the DownloadService. Take note we're encapsulating a DynamicJasper feature here, not a Jasper. So if you have specific questions about these, make sure to search the DynamicJasper forums.

The Exporter
This is a custom wrapper to Jasper's JRXlsExporter. The purpose of this class is to encapsulate the exporting of the report to different formats. This isn't mandatory. You can remove the contents of export() and place it along with the DownloadService. Take note we're encapsulating a Jasper feature here, not a DynamicJasper. So if you have specific questions about these, make sure to search the Jasper forums.

The datasource
Here we provide a custom datasource made from in-memory list of Sales items. We use the DAO name here to indicate that the data can come from a DAO or other persistence means.


Our datasource returns a list of Sales. This is a simple Data Transfer Object for containing our data from the database.


Our application is now finished. We've managed to setup a simple Spring 3 MVC application. Then we added reporting using DynamicJasper. We've divided our application's concerns in various layers: controllers, services, DAO, layout, and exporter so that we can easily change implementation and custom processing. We've also leveraged Spring's MVC programming model via annotation.

To access the download page, enter the following URL:

If you want to download the report directly, enter the following URL:

The best way to learn further is to try the actual application.

Download the project
You can access the project site at Google's Project Hosting at

You can download the project as a Maven build. Look for the in the Download sections.

You can run the project directly using an embedded server via Maven.
For Tomcat: mvn tomcat:run
For Jetty: mvn jetty:run

If you want to learn more about Spring MVC and Jasper, feel free to read my other tutorials in the Tutorials section.
StumpleUpon DiggIt! Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring 3 MVC - DynamicJasper Integration Tutorial ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share


  1. Great post! thank you for using DynamicJasper

  2. This comment has been removed by the author.

  3. This comment has been removed by the author.

  4. This comment has been removed by the author.

  5. Hello
    I have integrated Dynamic Reports with my Srpring 3.0 Project.Here i have seen some difficult to dsiplay the data in the Model
    This is my POJO

    public class Ent {
    private long Id;
    private long etId;
    protected List AVA ava;
    private ET et;
    private long sCount;

    I could able display all fields other than ava; This class is like bellow

    public class AVA{
    private String vchar;
    private Long vLong;
    private long eTypeId;

    How can display my ava.vchar , ava.vLong values?
    Any idea?

  6. You'll have to make a new class where you have to explicitly write all the properties. Then you have to map the values of Ent to this new class. For example:

    public class EntDTO() {
    private long Id;
    private long etId;
    private String vchar;
    private Long vLong;
    private long eTypeId;
    private ET et;
    private long sCount;

    EntDTO entDTO = new EntDTO();
    ... etc.

  7. Ok finally i resolved in list inside list problem using Map.
    Now i could able to generate reports using jasperviewer and genarate pdf,html formats. But I need display the report on my jsp (i.e in HTML format) later user could download either in pdf or what else he want. How can i displays the report on JSP page?

  8. finally this link resolves my problem now i could able to display my report result on my jsp

  9. i need to pass the parameters in the query string dynamically to the jrxml. can u please help me out.

  10. I added poi-3.7-20101029 jar to export xls formate report.But iam getting this error.How to resolve this?

    java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFRichTextString.applyFont(IILorg/apache/poi/hssf/usermodel/HSSFFont;)V
    at net.sf.jasperreports.engine.export.JRXlsExporter.getRichTextString(
    at net.sf.jasperreports.engine.export.JRXlsExporter.setRichTextStringCellValue(
    at net.sf.jasperreports.engine.export.JRXlsExporter.createTextCell(
    at net.sf.jasperreports.engine.export.JRXlsExporter.exportText(
    at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportPage(
    at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportReportToStream(
    at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportReport(
    at com.jbent.peoplecentral.model.manager.DynamicJasperManagerImpl.export(
    at com.jbent.peoplecentral.controller.DynamicJasperReportController.export(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)

  11. Make sure the POI version you're using is the version compatible with Jasper and DynamicJasper. There are cases where new versions of POI aren't compatible with Jasper. In that case you have to use an older jar

  12. @Sri, check my other tutorials for Jasper/DynamicJasper integration. There's a tutorial that demonstrates how to pass an HQL query

  13. Hello
    Thanks for such nice tutorials.
    I need to make a confirmation report in which I do not need any table
    My need is to represent only one value for any field
    So please tell me how can we do??

  14. @Gaurav, DynamicJasper is mainly designed for tabular data. If what you need is something beyond tabular, ie. a specific design, you have to do it with Jasper. Use IReport to design the report template. Try checking the following guide:

  15. Hello Sir Thanks for reply
    I sent you one mail on ur email id "", please reply me

  16. Hi krams I want to generate a pdf in a manner that it asks for save as dialogue.Can u pls help on that?

  17. @Anonymous, you can create a button "Save As Pdf" in your web application. Then on that button trigger the controller that generates the Pdf.

  18. Hello,
    Nice to find such tutorial , thank you very much for your efforts.
    I am using jasperreport 3.7.6 with the framework seam 2 and i am doing well . Now i am trying to integrate JasperDynamic , my question is it possible to work with this latter ?

    1. DynamicJasper should work with JasperReports regardless of your framework. If you can use Jasper, you can use DynamicJasper

    2. Thank you very much for your reply.
      I appreciate your generousness and kindness profoundly.
      Best wishes

  19. I opened this project in NetBenas and run it on integrated Apache TomCat and get this error in browser:

    HTTP Status 404 - /

    type Status report

    message /

    description The requested resource (/) is not available.
    Apache Tomcat/7.0.22

    Any advices pls?

  20. Very nice post. Good job.

    @Anonymous Use url http://localhost:8080/spring-djasper-integration/krams/main/download

  21. hi,
    i have a problem that my Data object is like this

    public class CandidateExcelModel {
    private int id;
    private String name; //varchar(50)
    private String email; // varchar(100)
    private Date dob; // date
    private List skill =new ArrayList();
    in this skill of list type and variable which can change time to time
    need help

  22. hi,
    i have a problem that my Data object is like this

    public class CandidateExcelModel {
    private int id;
    private String name; //varchar(50)
    private String email; // varchar(100)
    private Date dob; // date
    private List skill =new ArrayList();
    in this skill of list type and variable which can change time to time
    need help

  23. It works great in localhost but online doesnt download the file, instead shows an 404 error

  24. I have read your blog its very attractive and impressive. I like it your blog.

    Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training Java online training

    spring training in chennai spring hibernate training in chennai

  25. If you want your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (even if they're dating somebody else now) you must watch this video
    right away...

    (VIDEO) Text Your Ex Back?

  26. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    core java training in Electronic City

    Hibernate Training in electronic city

    spring training in electronic city

    java j2ee training in electronic city

  27. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
    Java training in Chennai

    Java training in Bangalore

  28. Subhanallah, this is a very good article. Give me awareness. Because all this time I always had a lot of good intentions, but after I got the things I could share.

    Obat Herbal Emfisema
    Obat Nyeri Lutut
    Obat Hipertiroid
    Cara Mengatasi Tinnitus
    Obat Sakit Maag

  29. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing..
    Believe me I did wrote an post about tutorials for beginners with reference of your blog. 

    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

  30. The article is so informative. This is more helpful for our
    software testing training courses
    selenium classes Thanks for sharing