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

Connection to Amazon Neptune endpoint from EKS during development

This small article will describe how to connect to Amazon Neptune database endpoint from your PC during development. Amazon Neptune is a fully managed graph database service from Amazon. Due to security reasons direct connections to Neptune are not allowed, so it's impossible to attach a public IP address or load balancer to that service. Instead access is restricted to the same VPC where Neptune is set up, so applications should be deployed in the same VPC to be able to access the database. That's a great idea for Production however it makes it very difficult to develop, debug and test applications locally. The instructions below will help you to create a tunnel towards Neptune endpoint considering you use Amazon EKS - a managed Kubernetes service from Amazon. As a side note, if you don't use EKS, the same idea of creating a tunnel can be implemented using a Bastion server . In Kubernetes we'll create a dedicated proxying pod. Prerequisites. Setting up a tunnel.

Notes on upgrade to JSF 2.1, Servlet 3.0, Spring 4.0, RichFaces 4.3

This article is devoted to an upgrade of a common JSF Spring application. Time flies and there is already Java EE 7 platform out and widely used. It's sometimes said that Spring framework has become legacy with appearance of Java EE 6. But it's out of scope of this post. Here I'm going to provide notes about the minimal changes that I found required for the upgrade of the application from JSF 1.2 to 2.1, from JSTL 1.1.2 to 1.2, from Servlet 2.4 to 3.0, from Spring 3.1.3 to 4.0.5, from RichFaces 3.3.3 to 4.3.7. It must be mentioned that the latest final RichFaces release 4.3.7 depends on JSF 2.1, JSTL 1.2 and Servlet 3.0.1 that dictated those versions. This post should not be considered as comprehensive but rather showing how I did the upgrade. See the links for more details. Jetty & Tomcat. JSTL. JSF & Facelets. Servlet. Spring framework. RichFaces. Jetty & Tomcat First, I upgraded the application to run with the latest servlet container versio