Struts 2 & Jasper Report integration example project in eclipse to generate reports

This tutorial shows that how to generate dynamic reports using Jasper Reports in struts 2 with out struts2-jasperreports-plugin. Jasper Reports uses XML templates to generate reports that can be saved as PDF or CSV, HTML, XLS. In this example, let us create jasper report for the items whose stock is greater than or equal to the input quantity. Assume that strut 2 is configured in eclipse for this project.

Before continuing to this tutorial, let us see the Jars used in this tutorial

Jars Used  for this example
commons-beanutils-1.9.0.jar
commons-codec-1.5.jar
commons-collections-3.2.1.jar
commons-digester-2.1.jar
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-javaflow-20060411.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-logging-api-1.1.jar
itextpdf-5.5.0.jar
jasper-compiler-jdt.jar
jasperreports-6.0.0.jar
jasperreports-fonts-6.0.0.jar
jasperreports-javaflow-6.0.0.jar

Direct link to download the above JasperReport Libraries

http://sourceforge.net/projects/jasperreports/files/jasperreports/

Steps to generate a report using JasperReports with struts 2

1. Create JRXML (JRStock.jrxml) which is a reusable template thst can be used by Jasper report engine to populate data from the database. This XML template includes various sections like Title, queryString, Page Header/Footer, Column Header/Footer, etc..
The XML template can be created by using IReports OR by editing the existing XML template file as per your requirement. The JRXML file(JRStock.jrxml) used in this example is given below.

JRStock.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="StockReport" pageWidth="500" pageHeight="600" columnWidth="450" leftMargin="5" rightMargin="5" topMargin="10" bottomMargin="1">
<reportFont name="Arial" isDefault="true" fontName="Arial" size="11" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
<parameter name="Title" class="java.lang.String"/>
<parameter name="qty" class="java.lang.Integer"/>
<queryString>
	<![CDATA[select itemcode, itemname, stock from stock_master where stock>=$P{qty}]]>
</queryString>
<field name="itemcode" class="java.lang.String"/>
<field name="itemname" class="java.lang.String"/>
<field name="stock" class="java.lang.Integer"/>
<title>
<band height="50" splitType="Stretch">
	<textField isBlankWhenNull="true">
	<reportElement x="40" y="0" width="370" height="30"/>
	<textElement textAlignment="Center">
	<font reportFont="Arial" size="22"/>
	</textElement>
	<textFieldExpression class="java.lang.String"><![CDATA[$P{Title}]]></textFieldExpression>
	</textField>
</band>
</title>
<pageHeader>
<band height="20" splitType="Stretch">
	<textField>
	<reportElement mode="Opaque" x="0" y="5" width="490" height="15" forecolor="#FFFFFF" backcolor="#777765"/>
	<textElement textAlignment="Center">
	<font reportFont="Arial"/>
	</textElement>
	<textFieldExpression class="java.lang.String"><![CDATA["Items whose stock is greater than or equal to " + String.valueOf($P{qty})]]></textFieldExpression>
	</textField>
</band>
</pageHeader>
<columnHeader>
   <band height="20" splitType="Stretch">
	<staticText>
	<reportElement mode="Opaque" x="0" y="4" width="170" height="15" backcolor="#CBB453"/>
	<textElement textAlignment="Left">
	<font reportFont="Arial"/>
	</textElement>
	<text><![CDATA[Item Code]]></text>
	</staticText>
	<staticText>
	<reportElement positionType="Float" mode="Opaque" x="170" y="4" width="170" height="15" backcolor="#CBB453"/>
	<textElement>
	<font reportFont="Arial"/>
	</textElement>
	<text><![CDATA[Item Name]]></text>
	</staticText>
	<staticText>
	<reportElement positionType="Float" mode="Opaque" x="340" y="4" width="150" height="15" backcolor="#CBB453"/>
	<textElement>
	<font reportFont="Arial"/>
	</textElement>
	<text><![CDATA[Stock]]></text>
	</staticText>
    </band>
</columnHeader>
<detail>
   <band height="20" splitType="Stretch">
	<textField>
	<reportElement x="0" y="4" width="170" height="15"/>
	<textElement textAlignment="Left"/>
	<textFieldExpression class="java.lang.String"><![CDATA[$F{itemcode}]]></textFieldExpression>
	</textField>
	<textField isStretchWithOverflow="true">
	<reportElement positionType="Float" x="170" y="4" width="170" height="15"/>
	<textElement/>
	<textFieldExpression class="java.lang.String"><![CDATA[$F{itemname}]]></textFieldExpression>
	</textField>
	<textField isStretchWithOverflow="true">
	<reportElement positionType="Float" x="340" y="4" width="150" height="15"/>
	<textElement/>
	<textFieldExpression class="java.lang.Integer"><![CDATA[$F{stock}]]></textFieldExpression>
	</textField>
   </band>
</detail>
<pageFooter>
    <band height="40" splitType="Stretch">
	<textField>
	<reportElement x="200" y="20" width="85" height="15"/>
	<textElement textAlignment="Right"/>
	<textFieldExpression class="java.lang.String"><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
	</textField>
	<textField evaluationTime="Report">
	<reportElement x="285" y="20" width="75" height="15"/>
	<textElement textAlignment="Left"/>
	<textFieldExpression class="java.lang.String"><![CDATA[" of " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
	</textField>
    </band>
</pageFooter>
<summary>
   <band height="35" splitType="Stretch">
	<textField isStretchWithOverflow="true">
	<reportElement x="175" y="20" width="165" height="15"/>
	<textElement textAlignment="Center">
	<font reportFont="Arial"/>
	</textElement>
	<textFieldExpression class="java.lang.String"><![CDATA["Total Number of Items " +
	String.valueOf($V{REPORT_COUNT})]]></textFieldExpression>
	</textField>
    </band>
</summary>
</jasperReport> 

2. Place the XML template in a filesystem (/jasper/JRStock.jrxml under WebContent folder). Compile the XML template using using java code.The following code compiles the JRStock.jrxml and creates JREStock.jasper in the same folder jasper.

JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper")); 

You can use this compiled version of XML template multiple times with different sets of parameters & data to create dynamic report

3. Load the .jasper file with JRLoader.loadObjectFromFile method which returns the JasperReport instance.

	File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
		// If compiled file is not found, then compile XML template
		if (!reportFile.exists()) {
		           JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
		    }
	    	JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
		   return jasperReport;
		} 

4. Now pass the jasperReport instance, parameters and connection object to methods like JasperRunManager.runReportToPdf(), JasperManager.fillReport() to generate the report in any formats such as PDF or HTML.

Now let us see the complete code

The following JSP (Report1.jsp) & Action Code (JasperAction that extends ActionSupport) is to capture quantity & format of the report

Report1.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Jasper Report Example</title>

</head>
<body>

<s:actionerror/>

<s:form name="reportForm" action="jasperTest.action" metod="post" >

<TABLE id="reptbl" width="350px" border="1">
  <TR>
  <td>
	Enter Quantity : <s:textfield name="qty"  label="Stock"/> <s:submit  value="Generate Stock Report" type="button"/>
 </td>
 <td>
 <s:radio label="format" name="rptFmt" list="#{'html':'HTML','pdf':'PDF'}" value="pdf" />
 </td>

</TR>

</TABLE>	

</s:form>

</body>
</html> 

JasperAction.java

package net.javaonline.controller;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;

public class JasperAction extends ActionSupport {

	private Map<String, Object> param=null;

	private String qty;
	private String rptFmt;

	public String getRptFmt() {
		return rptFmt;
	}

	public void setRptFmt(String rptFmt) {
		this.rptFmt = rptFmt;
	}

	public String getQty() {
		return qty;
	}

	public void setQty(String qty) {
		this.qty = qty;
	}

	public Map<String, Object> getParam() {
		return param;
	}

	public void setParam(Map<String, Object> param) {
		this.param = param;
	}

	public String execute() throws Exception {

        try {
    		param = new HashMap();
    		param.put("qty", new Integer(qty));
    		param.put("Title", "Stock Details");
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS;
    }

}

Now let us see the action code (LoadJasperReportAction that extends StrutsResultSupport) for database connection with mySql database, generating dynamic jasper report in HTML, PDF format and etc…based on the input.

LoadJasperReportAction.java

package net.javaonline.controller;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.naming.NamingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
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.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.util.JRLoader;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;

public class LoadJasperReportAction extends StrutsResultSupport {

    protected String parameters;
    protected String rptFormat;

	public String getRptFormat() {
		return rptFormat;
	}

	public void setRptFormat(String rptFormat) {
		this.rptFormat = rptFormat;
	}

	public String getParameters() {
		return parameters;
	}

	public void setParameters(String parameters) {
		this.parameters = parameters;
	}

	@Override
    protected void doExecute(String arg0, ActionInvocation arg1)
			throws Exception {
    	try {

    		String reportFileName = "JRStock";
    		String reportFormat ="";

    		Connection conn = null;
    		try {
    			try {

    				 Class.forName("com.mysql.jdbc.Driver");
    			 	} catch (ClassNotFoundException e) {
    			 		System.out.println("Please include Classpath Where your MySQL Driver is located");
    			 		e.printStackTrace();
    			 	}  

   			 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","j123456");

    		 if (conn != null)
    		 {
    			 System.out.println("Database Connected");
    		 }
    		 else
    		 {
    			 System.out.println(" connection Failed ");
    		 }

    			HttpServletRequest request = ServletActionContext.getRequest();
    			HttpServletResponse response = ServletActionContext.getResponse();

    			ValueStack stack = arg1.getStack();

   			   rptFormat = conditionalParse(rptFormat, arg1);
		       reportFormat=(String)stack.findValue(rptFormat);

		       System.out.println("Format " + reportFormat + "  -- " + rptFormat);

   			   HashMap hmParams=(HashMap)stack.findValue(parameters);

    			 parameters = conditionalParse(parameters, arg1);

       			JasperReport jasperReport = getCompiledFile(reportFileName, request);

	    		if (reportFormat.equalsIgnoreCase("html") ) {

	    			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, hmParams, conn);
	    			generateReportHtml(jasperPrint, request, response); // For HTML report

	    		}

	    		else if  (reportFormat.equalsIgnoreCase("pdf") )  {

	    			generateReportPDF(response, hmParams, jasperReport, conn); // For PDF report

	    		    }

    		   } catch (Exception sqlExp) {

    			   System.out.println( "Exception::" + sqlExp.toString());

    		   } finally {

		    		try {

		    		if (conn != null) {
			    		conn.close();
			    		conn = null;
		    		}

		    		} catch (SQLException expSQL) {

		    			System.out.println("SQLExp::CLOSING::" + expSQL.toString());

		    		}

    		       }

    			} catch (Exception e) {

    	            e.printStackTrace();

    			}

    }

    private JasperReport getCompiledFile(String fileName, HttpServletRequest request) throws JRException {
		File reportFile = new File( request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
		// If compiled file is not found, then compile XML template
		if (!reportFile.exists()) {
		           JasperCompileManager.compileReportToFile(request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jrxml"),request.getSession().getServletContext().getRealPath("/jasper/" + fileName + ".jasper"));
		    }
	    	JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile.getPath());
		   return jasperReport;
		} 

		private void generateReportHtml( JasperPrint jasperPrint, HttpServletRequest req, HttpServletResponse resp) throws IOException, JRException {
			Map imagesMap = new HashMap();
			JRHtmlExporter exporter = new JRHtmlExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter( JRExporterParameter.OUTPUT_WRITER, resp.getWriter());
			exporter.exportReport();
		}

		private void generateReportPDF (HttpServletResponse resp, Map parameters, JasperReport jasperReport, Connection conn)throws JRException, NamingException, SQLException, IOException {
			byte[] bytes = null;
			bytes = JasperRunManager.runReportToPdf(jasperReport,parameters,conn);
			resp.reset();
			resp.resetBuffer();
			resp.setContentType("application/pdf");
			resp.setContentLength(bytes.length);
			ServletOutputStream ouputStream = resp.getOutputStream();
			ouputStream.write(bytes, 0, bytes.length);
			ouputStream.flush();
			ouputStream.close();
		} 

 } 

struts.xml file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<constant name="struts.enable.DynamicMethodInvocation" 	value="false" />
	<constant name="struts.devMode" value="false" />

	<package name="default" extends="struts-default" namespace="/">

	   <result-types>
    		<result-type name="jasper1" class="net.javaonline.controller.LoadJasperReportAction"/>
	   </result-types>

	   <action name="jasperTest" class="net.javaonline.controller.JasperAction">
		<result name="success" type="jasper1">
		    <param name="parameters">param</param>
		    <param name="rptFormat">rptFmt</param>
		</result>
	    </action>

	</package>		

</struts> 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Struts2JasperExample</display-name>
  <welcome-file-list>
    <welcome-file>/Report1.jsp</welcome-file>
  </welcome-file-list>
 <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

</web-app> 

MySql Database used in this example : test
Table used in this example : stock_master

DDL to create the table :

 create table stock_master1 (itemcode varchar(10), itemname varchar(50), stock smallint);

Run the project by calling

http://localhost:8080/Jasper/

jasper input

Enter quantity (for e.g. 50) and Select PDF and click on GenerateJasperReport button

jasper result

 

Reference : http://struts.apache.org/docs/jasperreports-tutorial.html

The above example jasper project can be downloaded from Struts2JasperExample.war

You may also like

Leave a Reply

4 Comments on "Struts 2 & Jasper Report integration example project in eclipse to generate reports"


Guest
Amol
8 months 2 days ago

Would be better if there is comments in the code?? Otherwise good exapmle…..

Guest
abhijeet
9 months 7 days ago

can u help me to fetch jasper report in excel same integration struts 2 & jasper report in eclipse. plj help me .

Guest
Lingeswar
1 year 6 months ago

Please send me this code war/rar file. the download link is not working