Calling Jasper Report From Java Web Application using JSF 2.0

Creating Jasper Reports is very easy, especially with the iReport, but calling those reports from JSF or any other web framework could be a little tricky for new users.

Here you can learn how to call Jasper Report(.jasper file) from JSF Page. You can export a report in the desired format (HTML, PDF, RTF, EXCEL).

ReportConfigUtil is a utility class for JasperReports. It is used for compiling the report, filling the jasper file with data and exporting the report.

package com.bari.report.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.sql.*;

import javax.servlet.ServletContext;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

public class ReportConfigUtil {

    /**
     * PRIVATE METHODS
     */
    private static void setCompileTempDir(ServletContext context, String uri) {
        System.setProperty("jasper.reports.compile.temp", context.getRealPath(uri));
    }

    /**
     * PUBLIC METHODS
     */
    public static boolean compileReport(ServletContext context, String compileDir, String filename) throws JRException {
        String jasperFileName = context.getRealPath(compileDir + filename + ".jasper");
        File jasperFile = new File(jasperFileName);

        if (jasperFile.exists()) {
            return true; // jasper file already exists, do not compile again
        }
        try {
            // jasper file has not been constructed yet, so compile the xml file
            setCompileTempDir(context, compileDir);

            String xmlFileName = jasperFileName.substring(0, jasperFileName.indexOf(".jasper")) + ".jrxml";
            JasperCompileManager.compileReportToFile(xmlFileName);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static JasperPrint fillReport(File reportFile, Map<String, Object> parameters, Connection conn) throws JRException {
        parameters.put("BaseDir", reportFile.getParentFile());

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFile.getPath(), parameters, conn);

        return jasperPrint;
    }

    public static String getJasperFilePath(ServletContext context, String compileDir, String jasperFile) {
        return context.getRealPath(compileDir + jasperFile);
    }

    private static void exportReport(JRAbstractExporter exporter, JasperPrint jasperPrint, PrintWriter out) throws JRException {
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);

        exporter.exportReport();
    }

    public static void exportReportAsHtml(JasperPrint jasperPrint, PrintWriter out) throws JRException {
        JRHtmlExporter exporter = new JRHtmlExporter();
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
        exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
        exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        exporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING, "ISO-8859-9");
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "/SampleReportJSF/servlets/image?image=");//SampleReportJSF is the name of the project

        exportReport(exporter, jasperPrint, out);
    }

    public static void exportReportAsExcel(JasperPrint jasperPrint, PrintWriter out) throws JRException, FileNotFoundException, IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        OutputStream outputfile = new FileOutputStream(new File("d:/output/JasperReport1.xls"));//make sure to have the directory. excel file will export here
        
        // coding For Excel:
        JRXlsExporter exporterXLS = new JRXlsExporter();
        exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
        exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, output);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
        exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        exporterXLS.exportReport();
        outputfile.write(output.toByteArray());
    }
}

AbstractReportBean is an abstract java class, containing the prepareReport() method and abstract methods.

package com.bari.report.common;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.sql.*;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;

import com.bari.report.util.ReportConfigUtil;
import dao.Database;

public abstract class AbstractReportBean {

    public enum ExportOption {

        PDF, HTML, EXCEL, RTF
    }
    private ExportOption exportOption;
    private final String COMPILE_DIR = "/report/design/";
    //private String compileFileName = "productlist";//name of your compiled report file
    private String message;

    public AbstractReportBean() {
        super();
        setExportOption(ExportOption.PDF);
    }

    protected void prepareReport() throws JRException, IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

        ServletContext context = (ServletContext) externalContext.getContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        ReportConfigUtil.compileReport(context, getCompileDir(), getCompileFileName());

        File reportFile = new File(ReportConfigUtil.getJasperFilePath(context, getCompileDir(), getCompileFileName() + ".jasper"));

        ///////////////////
        Connection conn = null;
        try {
            conn = Database.getConnection();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        /////////////////////

        JasperPrint jasperPrint = ReportConfigUtil.fillReport(reportFile, getReportParameters(), conn);

        if (getExportOption().equals(ExportOption.HTML)) {
            ReportConfigUtil.exportReportAsHtml(jasperPrint, response.getWriter());
        } else if (getExportOption().equals(ExportOption.EXCEL)) {
            ReportConfigUtil.exportReportAsExcel(jasperPrint, response.getWriter());
        } else {
            request.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
            response.sendRedirect(request.getContextPath() + "/servlets/report/" + getExportOption());
        }

        FacesContext.getCurrentInstance().responseComplete();
    }

    public ExportOption getExportOption() {
        return exportOption;
    }

    public void setExportOption(ExportOption exportOption) {
        this.exportOption = exportOption;
    }

    protected Map<String, Object> getReportParameters() {
        return new HashMap<String, Object>();
    }

    protected String getCompileDir() {
        return COMPILE_DIR;
    }

    protected abstract String getCompileFileName();

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

ReportsBean is a JSF managed bean. It extends AbstractReportBean, overrides the abstract methods and calls prepareReport() method.

package com.bari.report.bean;

import java.util.HashMap;
import java.util.Map;
import com.bari.report.common.AbstractReportBean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "reportsBean")
@SessionScoped

public class ReportsBean extends AbstractReportBean {

    private final String COMPILE_FILE_NAME = "productlist";

    @Override
    protected String getCompileFileName() {
        return COMPILE_FILE_NAME;
    }

    @Override
    protected Map<String, Object> getReportParameters() {
        Map<String, Object> reportParameters = new HashMap<String, Object>();

        reportParameters.put("rtitle", "Hello JasperReports");

        return reportParameters;
    }

    public String execute() {
        try {
            super.prepareReport();
        } catch (Exception e) {
            // make your own exception handling
            e.printStackTrace();
        }

        return null;
    }
}

Database.java class for handling database connection

package dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class Database {

    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/dbname",
                    "root", "dbpass");
            return con;
        } catch (Exception ex) {
            System.out.println("Database.getConnection() Error -->" + ex.getMessage());
            return null;
        }
    }

    public static void close(Connection con) {
        try {
            con.close();
        } catch (Exception ex) {
        }
    }
}

Change your web.xml with the following configuration

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
    
    
    
    <!-- JasperReports Servlet -->
    <servlet>
        <servlet-name>PdfServlet</servlet-name>
        <servlet-class>net.sf.jasperreports.j2ee.servlets.PdfServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>JExcelApiServlet</servlet-name>
        <servlet-class>net.sf.jasperreports.j2ee.servlets.JExcelApiServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>RtfServlet</servlet-name>
        <servlet-class>net.sf.jasperreports.j2ee.servlets.RtfServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ImageServlet</servlet-name>
        <servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>
    </servlet>
        <!-- JasperReports Servlet Mapping -->	
    <servlet-mapping>
        <servlet-name>PdfServlet</servlet-name>
        <url-pattern>/servlets/report/PDF</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>JExcelApiServlet</servlet-name>
        <url-pattern>/servlets/report/EXCEL</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>RtfServlet</servlet-name>
        <url-pattern>/servlets/report/RTF</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ImageServlet</servlet-name>
        <url-pattern>/servlets/image</url-pattern>
    </servlet-mapping>
</web-app>

Call report from your index.xhtml page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Report</title>
    </h:head>
    <h:body>
        <f:view>			
            <h:form id="form" target="_blank">
                <h:outputLabel>Export Report</h:outputLabel>
                <h:selectOneRadio value="#{reportsBean.exportOption}">
                    <f:selectItem itemValue="PDF" itemLabel="PDF"/>
                    <f:selectItem itemValue="HTML" itemLabel="HTML"/>
                    <f:selectItem itemValue="EXCEL" itemLabel="EXCEL"/>
                    <f:selectItem itemValue="RTF" itemLabel="RTF"/>
                </h:selectOneRadio>
                <h:commandButton  action="#{reportsBean.execute}" value="Get Report" />
            </h:form>
        </f:view>
    </h:body>
</html>

Ref: http://www.jroller.com/hakan/entry/jasperreports_and_jsf_integration

Another solution for JSF is JasperReports JSF Plugin.
JasperReports JSF Plugin is a library that offers some JSF components to permit an easy integration of JSF web applications with the famous JasperReports report engine. Although I don’t have tried this yet, you can try. Best of luck.

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

43,299` Total Views

10 comments

  • how can i put value in parameter form application ,
    if i use getter setter which bean i can use ReportsBean or AbstractReportBean

    • Use ReportsBean, add properties and create getter and setter methods.

      • i try to like that.
        reportParameters.put(“stdRoll”, getRoll());
        but i faces this problem
        Exception is occured in ReportsBean————–>Not supported yet.

        • now try just copy your code without any application parameter there are also showing
          Exception is occured in ReportBean——–>Unknown hyperlink target 0

          • i faced this problem…. when i call report from application
            java.lang.NoClassDefFoundError: Lorg/jfree/chart/plot/PlotOrientation;

  • thanks. thats great your implementation.

    How can I instead of generate pdf or xls, open the jasper report in screen ? I mean the user clicks on a button and see the jasper report at screen.

    thanks

  • I am getting the below error while running the above code.Kindly let me know where to place the JASPER file
    net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: D:\Softwares\springsource\vfabric-tc-server-developer-2.9.5.SR1\base-instance\wtpwebapps\portal\pages\report1.jrxml (The system cannot find the file specified)

  • Muhammad Raza Saleem

    hi
    I am facing this exception i use your above code in jsf 2.2 with jasper

    java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
    javax.faces.FacesException: #{reportsBean.genarateReport()}: java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
    Caused by: javax.faces.el.EvaluationException: java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    … 34 more
    Caused by: java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:270)
    at net.sf.jasperreports.engine.util.JRClassLoader.loadClassForRealName(JRClassLoader.java:157)
    at net.sf.jasperreports.engine.util.JRClassLoader.loadClassForName(JRClassLoader.java:115)
    at net.sf.jasperreports.engine.JasperCompileManager.getCompiler(JasperCompileManager.java:508)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:212)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:145)
    at model.beans.ReportsBean.genarateReport(ReportsBean.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    … 35 more
    Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.control.CompilationFailedException
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1761)
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1611)
    … 56 more

  • Muhammad Raza Saleem

    Hi
    I use your code and i am facing thsi exception in netbeans 8
    java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException

    Please help me its urgent.

    thnaks

Leave a Reply

Your email address will not be published. Required fields are marked *


1 × eight =