Skip to main content

DynamicReports and Spring MVC integration

This is a tutorial on how to exploit DynamicReports reporting library in an existing Spring MVC based web application. It's a continuation to the previous post where DynamicReports has been chosen as the most appropriate solution to implement an export feature in a web application (for my specific use case). The complete code won't be provided here but only the essential code snippets together with usage remarks. Also I've widely used this tutorial that describes a similar problem for an alternative reporting library.

So let's turn to the implementation description and start with a short plan of this how-to:
  1. Adding project dependencies.
  2. Implementing the Controller part of the MVC pattern.
  3. Modifying the View part of the MVC pattern.
  4. Modifying web.xml.
Adding project dependencies
I used to apply Maven Project Builder throughout my Java applications, thus the dependencies will be provided in the Maven format.

Maven project pom.xml file:

    net.sourceforge.dynamicreports
    dynamicreports-core
    2.3.1
    
        
            net.sf.barcode4j
            barcode4j
        
        
            com.sun.xml.bind
            jaxb-impl
        
        
            org.codehaus.castor
            castor
        
        
            eclipse
            jdtcore
        
        
            xml-apis
            xml-apis
        
        
            jfree
            jfreechart
        
        
            jfree
            jcommon
        
        
            bouncycastle
            bcprov-jdk14
        
        
            org.apache.poi
            poi-ooxml
        
    


    net.sourceforge.jexcelapi
    jxl
    2.6.12

Here I wittingly missed other dependencies (including Spring, etc) as this post is more about applying DynamicReports to existing Spring based application. I widely used exclusions in order to minimize the final build size and left only those dependencies that are required for exporting to Excel and PDF formats. Whether you have other needs, you'll have to modify this code for yourself.

Implementing the Controller part of the MVC pattern
First of all I need to mention there is an alternative way to integrate DynamicReports with your Java web application that is a more generic one - using Servlets. I'm going to cover this approach in the next post, meanwhile you can refer to a short DynamicReports tutorial. Our current approach is based on Spring MVC features and is a more elegant solution.

ExportSearchController.java:
package org.lagivan.prototype.web.controller;

import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.exception.DRException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@Scope("session")
@RequestMapping("/export")
public class ExportSearchController {

    private static final Logger log =
            LoggerFactory.getLogger(ExportSearchController.class);

    private static final String PARAMETER_ITEM_NAME = "itemName";
    private static final String PARAMETER_TYPE = "type";
    private static final String VALUE_TYPE_PDF = "pdf";
    private static final String VALUE_TYPE_XLS = "xls";

    private static final Map<String, String> FILE_TYPE_2_CONTENT_TYPE = 
            new HashMap<String, String>();
    static {
        FILE_TYPE_2_CONTENT_TYPE.put(VALUE_TYPE_PDF, "application/pdf");
        FILE_TYPE_2_CONTENT_TYPE.put(VALUE_TYPE_XLS, "application/vnd.ms-excel");
    }

    @Autowired
    private SearchController searchController;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String fileType = request.getParameter(PARAMETER_TYPE);
        log.info("Exporting {} report", fileType);

        response.setContentType(FILE_TYPE_2_CONTENT_TYPE.get(fileType));
        OutputStream out = response.getOutputStream();
        try {
            JasperReportBuilder jrb = createJasperReport();

            if (VALUE_TYPE_PDF.equals(fileType)) {
                jrb.toPdf(out);
            } else if (VALUE_TYPE_XLS.equals(fileType)) {
                jrb.toExcelApiXls(out);
            }
        } catch (DRException e) {
            throw new ServletException(e);
        }
        out.close();
    }

    private JasperReportBuilder createJasperReport() {
        // Here use DynamicReports API to build a report 
        // and fill it with a JRDataSource.
        // I used SearchController session bean
        // to get required search results data.
    }
}

Here I widely used Spring annotations to register a Spring web controller, set its scope and map web requests to a specific handler method. As soon as method ExportSearchController.export is called on incoming web request, it generates an Excel or PDF output as a response using specified request parameters. Everything is quite straightforward and looks clear.

Implementing the View part of the MVC pattern
This part can be implemented using a variaty of ways in your application. We used to exploit JSF technology in our projects using RichFaces component library. Thus, I'll provide xhtml source code snippet that you will have to adapt to your own case. It's a page with search results that uses SearchController managed bean mentioned above to execute search functionality and to render search results data in a table component.

searchresults.xhtml:
<rich:dataTable id="searchresults-table" value="#{searchController.data}" width="100%">
    <rich:column style="vertical-align: top;" width="36px;">
        <f:facet name="header">
            <h:panelGroup>
                <h:outputLink title="Export to Excel"
                              value="#{facesContext.externalContext.requestContextPath}/web/export?type=xls">
                    <h:graphicImage style="border: none;" value="/icons/xls_16.png"/>
                </h:outputLink>
                <h:outputLink title="Export to PDF"
                              value="#{facesContext.externalContext.requestContextPath}/web/export?type=pdf">
                    <h:graphicImage style="border: none;" value="/icons/pdf_16.png"/>
                </h:outputLink>
            </h:panelGroup>
        </f:facet>
    </rich:column>
</rich:dataTable>

So you can see here is a column header where I added links to execute export functionality. Being clicked, a link produces HTTP request to your mapped handler method and returns HTTP response with a report document.

Modifying web.xml
Finally I've forgot to mention the last required change. Spring MVC requires DispatcherServlet to be registered in your web.xml to handle mapped requests properly. Actually you may have some issues here related to other Spring servlets. For example, I've already had a MessageDispatcherServlet registered in my application for the purpose of webservices. Thus, I had to add an empty spring-servlet.xml file and the following code snippet to my web.xml.

web.xml:

    spring
    org.springframework.web.servlet.DispatcherServlet
    1



    spring
    /web/*

Comments

  1. Thanks your posting. It is very helpful. Do you have any example on plain struts framework. I am using the Action class. It would be great if you provide any example.
    Small question related to JasperViewr. I am getting the JasperViewer window when the pdf is open in a separate window. And when I close the JasperViewer , it is closing the application server. I have used the jrb.toPdf(out). I don't know where to set the ExitOnClose option in the dynamic reports. Actually I don't want to view in the JasperViewer. I want to avoid completely and want to view only in the PDF. Do you have any idea ? Thanks, -R

    ReplyDelete
  2. I'm not planning to make an example for Struts as I don't have enough experience with Struts. But I assume it should be possible to add custom servlet there. Then you may find it valuable: http://lagivan.blogspot.com/2011/11/dynamicreports-and-cocoon-integration.html#servlet

    Regarding JasperViewer, it's jrb.show() method that opens JasperViewer window but not jrb.toPdf(). So make sure not to call show() method... If it's not your case, you'd better ask on the DynamicReports forum.

    ReplyDelete
  3. I use DynamicReports coupled with Spring 3. When my DynamicReportsController invokes .show() method, it shows up a JasperViewer frame on the server side. I removed the .show() method call and invoked jrb.toPdf(out), there is no error on the client browser but the Jasper report was not rendered on the client side either. I have also configured server property
    -Djava.awt.headless=true through the static block as follows:
    static {
    FILE_TYPE_2_CONTENT_TYPE.put(VALUE_TYPE_PDF, "application/pdf");
    FILE_TYPE_2_CONTENT_TYPE.put(VALUE_TYPE_HTML, "application/html");
    FILE_TYPE_2_CONTENT_TYPE.put(VALUE_TYPE_XLS, "application/vnd.ms-excel");
    System.setProperty("java.awt.headless", "true");
    }
    However, I still cannot see the report on the client browser. I would appreciate very much if someone could provide suggestions to make it success.

    Thanks in advance.
    Lee

    ReplyDelete
  4. I don't think you need to enable the headless mode as it's required for AWT tools that is not related to DynamicReports.

    You may have an issue with mapping your request URI to a method call. I did this using @RequestMapping annotations. You need to debug your application. Set a breakpoint inside the method that is mapped to a request URI (in my case the method is export), then open corresponding URL in your browser and check if you can trace the breakpoint. If not, you didn't map the request URI properly or you're using wrong URL. If yes, just debug further and solve the problem.

    ReplyDelete
  5. Debug did not show any problem.

    Here is the controller:

    @Controller
    @Scope("session")
    @RequestMapping("/export")
    public class DynamicReportsController {

    @RequestMapping(value = "/html", method = RequestMethod.GET)
    public void exportToHtml(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    response.setContentType("application/pdf");
    OutputStream out = response.getOutputStream();
    try {
    report().title(cmp.text("Report test")).toPdf(out);
    }
    catch (DRException e) {
    throw new ServletException(e);
    }
    out.close();
    }

    ReplyDelete
  6. The problem was caused by the following ajax call:

    $("#showReport").click(function(){
    var reportFileNames = "";
    $('#reportFileNameTable tbody tr').each(function() {
    reportFileNames = reportFileNames + $(this).find("td").find("li").html() + "; ";
    });
    var parameters = "rfn=" + reportFileNames;
    $.ajax({
    type: "GET",
    url: "export/report?" + parameters,
    success: function(data) {
    $('#htmlReport').html(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
    alert("error:" + textStatus + " exception:" + errorThrown);
    }
    });

    change to the following fixed the problem. A new browser shows the Pdf report. :-)

    $("#showReport").click(function(){
    var reportFileNames = "";
    $('#reportFileNameTable tbody tr').each(function() {
    reportFileNames = reportFileNames + $(this).find("td").find("li").html() + "; ";
    });
    var parameters = "rfn=" + reportFileNames;
    var url = "export/report?" + parameters;
    try {
    var child = window.open(url);
    child.focus();
    }
    catch (e) {
    }
    });

    ReplyDelete
  7. I'm glad you solved it because the server side code didn't contain any errors indeed.

    ReplyDelete
  8. BTW, you can post any code snippets here including xml. Just encode it before pasting using any html encoder available on the web, for example:

    http://www.opinionatedgeek.com/dotnet/tools/htmlencode/encode.aspx

    ReplyDelete
  9. Any GUI tool for Dynamic report as we can generate report via tool....@Sachin

    ReplyDelete

Post a Comment

Popular posts from this blog

Choosing Java reporting tool - part 2

I've provided a general overview of possible solutions to get a reporting/exporting functionality in the previous post. This is the second overview of alternatives based on JasperReports reporting engine.

Since the previous part I've done the following:
Implemented a simple report using both DynamicJasper and DynamicReports to compare them from technical side.Investigated JasperServer features and tried to implement a simple report for JasperServer instance (it appeared we already have a ready licensed installation of JasperServer that makes it unreasonable to install a fresh one).
First, the comparison results of Java libraries (DynamicJasper and DynamicReports):
Both libraries suffer from poor-quality or missing Java docs but they look a bit better in DynamicJasper.Taking into account the point 1, a developer has to use online documentation and to review the code. Here the code looks definitely nicer and more readable for DynamicReports. With respect t…

Do It Yourself Java Profiling

This article is a free translation of the Russian one that is a transcript of the Russian video lecture done by Roman Elizarov at the Application Developer Days 2011 conference.
The lecturer talked about profiling of Java applications without any standalone tools. Instead, it's suggested to use internal JVM features (i.e. threaddumps, java agents, bytecode manipulation) to implement profiling quickly and efficiently. Moreover, it can be applied on Production environments with minimal overhead. This concept is called DIY or "Do It Yourself". Below the lecture's text and slides begin.
Today I'm giving a lecture "Do It Yourself Java Profiling". It's based on the real life experience that was gained during more than 10 years of developing high-loaded finance applications that work with huge amounts of data, millions currency rate changes per second and thousands of online users. As a result, we have to deal with profiling. Application profiling is an i…