Thursday, December 30, 2010

Spring MVC 3 - Jasper: How to Use JasperReportsMultiFormatView

In this tutorial we will integrate Jasper reporting with a simple Spring 3 MVC application. We will provide a custom data source where Jasper will retrieve its data. We will use Spring's built-in JasperReportsMultiFormatView support to render our report in different formats. To design the report layout we will use iReport to create the template. This tutorial is a variation of the Spring 3 MVC - Jasper Integration Tutorial

What is Jasper Reports?
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.

Source: http://jasperforge.org/projects/jasperreports
What is iReport?
iReport is the free, open source report designer for JasperReports. Create very sophisticated layouts containing charts, images, subreports, crosstabs and much more. Access your data through JDBC, TableModels, JavaBeans, XML, Hibernate, CSV, and custom sources. Then publish your reports as PDF, RTF, XML, XLS, CSV, HTML, XHTML, text, DOCX, or OpenOffice.

Source: http://jasperforge.org/index.php?q=project/ireport
What is JasperReportsMultiFormatView?
The JasperReportsMultiFormatView allows for the report format to be specified at runtime. The actual rendering of the report is delegated to one of the other JasperReports view classes - the JasperReportsMultiFormatView class simply adds a wrapper layer that allows for the exact implementation to be specified at runtime.

Source: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jasper-reports-configuration-multiformat-view
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 that we will be generating:


This is just basic. You can add more features such as charts,custom calculations, and other report related functions with Jasper. If you need to design the layout, you can use iReport to do the job.

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

This controller declares three mappings:
/main - for showing the download page
/main/download?type=xxx - for retrieving the report where xxx is the format
Inside the doSalesMultiReport() method, notice we retrieve the datasource:

We then placed the datasource in the model:

We also placed the format in the model:

The view multiReport is declared on a separate XML file under /WEB-INF/jasper-views.xml
jasper-views.xml

We've declared a JasperReportsMultiFormatView bean. It has a reportDataKey property that references the datasource from the controller. It also has a reference to the Jasper template tree-template.jrxml

Let's complete our Spring MVC setup.

To enable Spring MVC we need to add it in the web.xml

web.xml

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

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

spring-servlet.xml

Notice we declared two view resolvers here: an InternalResourceViewResolver and an XmlViewResolver. If you've been following my other tutorials, you'll notice that we always declare an InternalResourceViewResolver only.

We must declare an extra view resolver this time to help Spring to choose the correct view to render our reports. If we just use InternalResourceViewResolver, all view references will point to /WEB-INF/jsp/ and will be appended with a .jsp extension. We don't want that because that location is for JSPs. Our report views are internal within Spring's package and we indicate that inside the /WEB-INF/jasper-views.xml file.

We're done with the spring-servlet.xml file.

By convention, we must declare an applicationContext.xml as well.

applicationContext.xml

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

Now we move to the crucial point of our tutorial. Remember earlier we had a reference to a template file named tree-template.jrxml

tree-template.jrxml (a partial view)

If you notice our report template is just plain XML! Nothing magical here. Actually we used a special tool to generate this XML template. It's called iReport. To get started with this tool, visit the Getting Started guide from JasperForge.

For this tutorial, we need to do the following:

1. Download and install iReport.

2. Run iReport

3. Go to File. Then click on New

4. Select the Tree template . Any template will do, even a blank one.


You should see a ready-made template:


5. We need to add four new fields in this layout. On the upper-left side, click on Fields.


6. Right-click and add four fields:


7. Make sure to set the correct types:
id: Long
name: String
price: Double
description: String

On the upper-right side, there's a panel where you can modify the properties of the fields we declared.


8. Now we need to drag each of those fields to the main layout. See below:


9. Then modify the title and subtitle. This isn't really mandatory. Just make sure you placed those four fields.


10. Click on the main layout again. On the right-side panel, you should see a list of properties for the main report layout. You need to change the default Language from Groovy to Java. Failure to do so will result to multiple compilation errors. Unless you know Groovy and familiar with its dependencies, it's best you stick with Java for now.


11. Save the document.

12. Now you need to locate that document. Copy and place it in the classpath of your web application. If you look carefully on the directory where the original document is saved, there are two images that had been saved as well. Make sure to copy them as well! Failure to copy them to your classpath will cause an Exception in the application.

Here's how our final directory should look like:

Remember we declared four fields in this layout. Where exactly do we get our data to fill-in these fields? It's assigned by the controller.

See that line:
JRDataSource datasource  = dataprovider.getDataSource();
That's where we get our data.

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.

SalesDAO

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

Our application is now finished. We've managed to setup a simple Spring 3 MVC application with reporting capabilities using Jasper. We've leveraged Spring's built-in JasperReportsMultiFormatView for rendering the reports in different formats. We also used iReport to design the report document and leveraged Spring's MVC programming model via annotation.

To access the download page, enter the following URL:
http://http://localhost:8080/spring-jasper-multiformat/krams/main
Here's a final look to our download page:
downloadpage.jsp

If you want to download the report directly, enter the following URL for XLS format:
http://localhost:8080/spring-jasper-multiformat/krams/main/download&type=xls
For PDF format, enter the following URL:
http://localhost:8080/spring-jasper-multiformat/krams/main/download&type=pdf
For HTML format, enter the following URL:
http://localhost:8080/spring-jasper-multiformat/krams/main/download&type=html
For CSV format, enter the following URL:
http://localhost:8080/spring-jasper-multiformat/krams/main/download&type=csv
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 http://code.google.com/p/spring-mvc-jasper-integration-tutorial/

You can download the project as a Maven build. Look for the spring-jasper-multiformat.zip 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! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3 - Jasper: How to Use JasperReportsMultiFormatView ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

26 comments:

  1. I tried spring-jasper-integration and spring-jasper-multiformat (maven build) tutorial and they work! But I'm still stuck on how to publish the images/graph using the method.

    I'd read from other forums that need to setup an ImageServlet, but I didn't get it through yet...

    Do you have any solution for Spring MVC + Jasper + Html and with images/graph?

    Thanks
    WdZul

    ReplyDelete
  2. Hi I was trying the example and downloaded it from here.But when I was trying to run it it says "Caused by: org.springframework.context.ApplicationContextException: Could not load JasperReports report from class path resource [tree-template.jrxml]; nested exception is java.io.FileNotFoundException: class path resource [tree-template.jrxml] cannot be opened because it does not exist"

    I can't understand it , how to put this .jrxml file in the class path . Please suggest ...

    ReplyDelete
  3. Hi I was trying the example and downloaded it from here.But when I was trying to run it it says "Caused by: org.springframework.context.ApplicationContextException: Could not load JasperReports report from class path resource [tree-template.jrxml]; nested exception is java.io.FileNotFoundException: class path resource [tree-template.jrxml] cannot be opened because it does not exist"

    I can't understand it , how to put this .jrxml file in the class path . Please suggest ...

    ReplyDelete
  4. @friend, you have to move the jrxml in the classpath. In the project, the classpath is at src/main/java folder

    ReplyDelete
  5. Thanks ..as always..this helped me tremendously

    ReplyDelete
  6. @wdzul Yes, you are rigth you can use the imageServlet but the next code just make it to display the images contained in the jasperreports.jar if you want see how to configure download my mods here:

    i just added the servlet in web.xml the reference of servlet:


    imageSvlt
    net.sf.jasperreports.j2ee.servlets.ImageServlet
    1


    imageSvlt
    /krams/image



    in jasper-views.xml added the maps and add the reference of map exporterParametersMap in the bean of multiReport

    util:map id="imagesMap" />









    i also make an upgrade of jasperreports version to 4.0.2

    in addition u can delete the imagesMap reference and try if it still functionallity. also if you realise the integration of external images like the tree1.png into html report let me know how u did

    Peace

    ReplyDelete
  7. Whatever you do, you document it in the form of a tutorial, that is indeed inspiring. Keep it up, man !

    ReplyDelete
  8. Hi i was trying the same example with my own.I am working on Ubuntu ans Jasper reports 4.5.0 with spring 3.0 ,Maven2.I am creating the jrxml file using the Jaspersoft studio i got the readymade tree template and i stucked there(exactly at step 5).I am unable to find how to add the fields to the tree template.According to yours you told that click on the upper left side and click on the fields.but i am not at all getting anything overthere.Can you please tell me how to add the fields to the tree template using jaspersoft studio.I am new to spring and jasper reports.

    Thanks in advance....

    ReplyDelete
  9. Hi I was trying the example and downloaded it from here.I compiled the jrxml file to get the .jasper file and copy the jrxml file to the web-inf classes folder(working with maven and under web-inf classes folder manually created by me to place the jrxml file) and i am running the project as run as maven install.When i run like this it shos that build success and it generated the war file.I copied this war file to the web apps folder of tomcat and started the tomcat and hitting the url as you mentioned above.It is not at all giving any exception and it is telling the 404 error the requested resourse is not available.Any thing wrong i have done or any more modifications are required.Can you please tell me.

    ReplyDelete
  10. @rupa (ssss), I suggest you checked an updated version of this guide first at http://krams915.blogspot.com/2012/01/spring-mvc-31-and-jasperreports-using_5116.html Then verify if you're still encountering problems.

    ReplyDelete
  11. Hi,
    I have gone through your tutorial but i didn't find how to install the ireport on ubuntu.I am using jaspersoft studio there i am getting the jrxml file but not able to get the report inspector where i can add fields and all..Can you please tell me which one is better to use and the procedure of using with Ubuntu and Eclipse (indigo) with spring maven.

    ReplyDelete
  12. @rupa, I noticed I haven't uploaded the instructions for Ubuntu yet. But basically it's the same steps as with Windows except you choose the tar.gz file

    ReplyDelete
  13. Hi,
    Very Thanks for giving the reply.I have installed the ireport on ubuntu and now its working fine.I am trying to generate the report using tree template and i have done everything adding columns and all but when i preview the report it is giving the exception as

    net.sf.jasperreports.engine.util.JRFontNotFoundException: Font 'Symbol' is not available to the JVM. See the Javadoc for more details.

    If i set the font to Serif then the report is generating.If i give Arial or Times-new-roman...etc it is giving the exception.I have gone through the net for finding the solution for this problem.But i didn't find the exact one.What i have to do to generate the report with all these fonts.Can you please tell me...And earlier itself i mentioned that i am working on Ubuntu and my jasperreports is 4.5.0

    ReplyDelete
  14. Good tutorial!!,
    Well, I have a problem. I need to change the filename of the report when the user download it. So I put the following sentence in the controller:

    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "inline; filename=Demo.csv");

    This is working wih IE7 but not with Crhome or Firefox.

    Could you please help me?

    ReplyDelete
    Replies
    1. Can you help me also,i am having the same problem

      Delete
  15. @Gabriel, why is the filename Demo.csv when your file type is PDF? Shouldn't it be Demo.pdf?

    ReplyDelete
  16. Hi Krams,

    While designing the report using ireport can i give the field name whatever i want or i have to give the attribute names in the entity class

    ReplyDelete
    Replies
    1. You have to name your Jasper Reports parameters after the names of your bean, otherwise your app will generate an error, because it wont find the property on the bean.

      Delete
  17. hi
    I have imported project as maven build in Spring tool suite.I am getting error as requested source not found.Pls help.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. hi
    is it possible to keep two beans at a time for two different jrxml file in jasper-views.xml

    since i have to generate around 100 pdf files and when i changed name to my rxml pdf name instead of tree-template.jrxml download.jsp page is failed to load resource not available error will be there on browser
    pls help me out i am really stuck with this problem frm last two days

    ReplyDelete
  20. 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

    ReplyDelete

  21. Your blog is very useful for me.I really like you post.Thanks for sharing.
    goldenslot

    ReplyDelete