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.

Source: http://dynamicjasper.com/

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.

Source: http://jasperforge.org/projects/jasperreports

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.

MainController

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

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

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

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

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.

DownloadService

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);
response.setContentType("application/vnd.ms-excel");
response.setContentLength(baos.size());

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.

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. 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:
http://localhost:8080/spring-djasper-integration/krams/main/download


If you want to download the report directly, enter the following URL:
http://localhost:8080/spring-djasper-integration/krams/main/download/xls

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-dynamicjasper-integration-tutorial/

You can download the project as a Maven build. Look for the spring-djasper-integration.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 3 MVC - DynamicJasper Integration Tutorial ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

93 comments:

  1. Great post! thank you for using DynamicJasper

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

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

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

    ReplyDelete
  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?

    ReplyDelete
  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();
    entDTO.setId(ent.getId())
    ... etc.

    ReplyDelete
  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?

    ReplyDelete
  8. finally this link resolves my problem now i could able to display my report result on my jsp
    http://dynamicjasper.com/2010/10/06/how-to-export-to-html/

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

    ReplyDelete
  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(JRXlsExporter.java:601)
    at net.sf.jasperreports.engine.export.JRXlsExporter.setRichTextStringCellValue(JRXlsExporter.java:582)
    at net.sf.jasperreports.engine.export.JRXlsExporter.createTextCell(JRXlsExporter.java:551)
    at net.sf.jasperreports.engine.export.JRXlsExporter.exportText(JRXlsExporter.java:410)
    at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportPage(JRXlsAbstractExporter.java:590)
    at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportReportToStream(JRXlsAbstractExporter.java:463)
    at net.sf.jasperreports.engine.export.JRXlsAbstractExporter.exportReport(JRXlsAbstractExporter.java:186)
    at com.jbent.peoplecentral.model.manager.DynamicJasperManagerImpl.export(DynamicJasperManagerImpl.java:222)
    at com.jbent.peoplecentral.controller.DynamicJasperReportController.export(DynamicJasperReportController.java:96)
    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)

    ReplyDelete
  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

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

    ReplyDelete
  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??
    Thanks

    ReplyDelete
  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: http://krams915.blogspot.com/2010/12/spring-3-mvc-jasper-integration.html

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

    ReplyDelete
  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?

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

    ReplyDelete
  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 ?

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

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

      Delete
  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?

    ReplyDelete
  20. Very nice post. Good job.

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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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?

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  31. outsourcingall.com Most Poplar Free Porn Training Center largest The coolest Free Porn Videos & Sex Movies Updated Daily. Update is a tube porn site with millions Online and offline real life porn cam

    ReplyDelete
  32. An iOS app can be a high-productive tool for your business that can help promote your brand among greater number of consumers.

    Mobile app Development Company in India

    ReplyDelete
  33. Software Development Company We specialize in Blockchain development, Artificial Intelligence, DevOps, Mobile App development, Web App development and all your customised online solutions. Get best impression at online by our services, we are familiar for cost effectiveness, quality, delivery and support.

    ReplyDelete
  34. Best place to learn Python in Bangalore!! myTectra!!
    Python training in Bangalore

    ReplyDelete
  35. Nice article.
    For data science training in bangalore,visit:
    Data science training in bangalore

    ReplyDelete
  36. vist here for know best devops training in bangalore
    DEVOPS TRAINING IN BANGALORE

    ReplyDelete
  37. professional bridal makeup artist in chennai Style Specializes in beauty bridal makeup and makes assured that individual bride should look like a princess.

    best bridal makeup artist in chennai

    ReplyDelete
  38. Software Development Company We specialize in Blockchain development, Artificial Intelligence, DevOps, Mobile App development, Web App development and all your customised online solutions. Get best impression at online by our services, we are familiar for cost effectiveness, quality, delivery and support.
    Blockchain Development Company Are you looking for a blockchain developer to meet your organization? Then it makes good sense to hire our expertized blockchain developer. Blockchain has become the most decentralized topic in different organizations.This technology creates a new doorway for payment which is exceedingly secure. It is a magnificent form of Database storage system useful to record information or data. This information can be automatically stored with the help of the cryptography mechanism furnishing more secure data. We will help you to develop and attach to a private blockchain where features that will be track and verify transaction and communication between different departments and stakeholders. The blockchain technology that supports Digital currencies and cryptocurrencies

    ReplyDelete
  39. I have perused your blog its appealing, I like it your blog and keep update.
    php development company,
    php development india,
    php application development,
    php website development,
    php web development,
    php framework,
    Thanks for sharing useful information article to us keep sharing this info

    ReplyDelete