Tuesday 16 February 2016

Struts with jasper Report Example

Hello Friends hope you all are fine.now its time to move towards struts framework.i will update about struts . i hope you all have basic understanding of struts framework.in this example i will be using Struts 2.x.


Struts  is also MVC Framework  like Spring.in this Example i will be integrating Jasper Report with Struts Framework. Enjoy Code guys.

Apart from struts 2.x distribution ,jasper Jars also required to  make application runnable.you can get jasper jars from http://community.jaspersoft.com/project/jasperreports-library/releases.

one additional jar is required struts2-jasperreports-plugin-2.3.jar


Project Structure will look like given below :


in Spring mvc we have model ,view,controller. where as Struts is also mvc. but we call controller as Action Class.

Action Class is given below :
package org.jasper;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;

public class StudentJasperAction extends ActionSupport {

/**
*
*/
private static final long serialVersionUID = 1L;

private Map<String, Object> param=null;

private String studId;
private String rptFmt;
 
public String getRptFmt() {
return rptFmt;
}

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





public String getStudId() {
return studId;
}

public void setStudId(String studId) {
this.studId = studId;
}

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<String,Object>();
   
    param.put("studid", new Integer(studId));
    param.put("Title", "Student  Details");
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS;
    }

 
}


 I have used StrutsResultSupport to  customize view.the below code render jasper report .
package org.jasper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.query.JRQueryExecuterFactory;
import net.sf.jasperreports.engine.util.JRProperties;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;

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

public class LoadJasperReportAction extends StrutsResultSupport {

protected String parameters;
protected String rptFormat;

protected String studId;

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;
}

public String findParam(String key, Map<String, Object> params) {
Object obj = params.get(key);
if (obj != null) {
String[] values = (String[]) obj;
return values.length > 0 ? values[0] : null;
}
return (String) obj;
}

@Override
protected void doExecute(String arg0, ActionInvocation arg1)
throws Exception {
ActionContext context = ActionContext.getContext();
Map<String, Object> params = context.getParameters();
String studentId = findParam("studId", params);

try {
String reportFileName = "StudentReport";
Connection conn = null;

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/studentdb",
"root", "admin!@#");

HttpServletRequest request = ServletActionContext.getRequest();

ValueStack stack = arg1.getStack();


parameters = conditionalParse(parameters, arg1);
String contextPath = request.getSession().getServletContext()
.getRealPath("/report/" + reportFileName + ".jrxml");
try {

InputStream input = new FileInputStream(new File(contextPath));

System.out.println("Context Path is  : =" + contextPath);
JasperDesign jasperDesign = JRXmlLoader.load(input);

System.out.println("Compiling Report Designs");

JasperReport jasperReport = JasperCompileManager
.compileReport(jasperDesign);

jasperReport.setProperty(
"net.sf.jasperreports.query.executer.factory.plsql",
"com.jaspersoft.jrx.query.PlSqlQueryExecuterFactory");

JRProperties.setProperty(
JRQueryExecuterFactory.QUERY_EXECUTER_FACTORY_PREFIX
+ "plsql",
"com.jaspersoft.jrx.query.PlSqlQueryExecuterFactory");
System.out.println("Creating JasperPrint Object");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("studId", studentId);

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

int pages = jasperPrint.getPages().size();
if (pages != 0) {
File f = new File("d:\\struts1.pdf");
f.createNewFile();

// Exporting the report
OutputStream output = new FileOutputStream(f);

JasperExportManager.exportReportToPdfStream(jasperPrint,
output);

System.out.println("Report Generation Complete");
} else {
System.out.println(" NO DATA FOUND TO EXPORT .....");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}

} catch (Exception e) {
e.printStackTrace();
}
}

}

Configration file is given below.

struts.xml

<?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="org.jasper.LoadJasperReportAction"/>
  </result-types>

  <action name="studentJasperCall" class="org.jasper.StudentJasperAction">
        <result name="success" type="jasper1">
            <param name="parameters">parameters</param>
            <param name="rptFormat">rptFmt</param>
        </result>
    </action>

</package>



</struts>

JSP PAGE : 

Student.jsp

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

</head>
<body>

<s:actionerror/>

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

<TABLE id="reptbl" width="400px" border="2">
  <TR>
  <td>
Enter Student id : <s:textfield name="studId" label="stud" /> <s:submit  value="Generate Student Report" type="button"/>
 </td>
 <td>
 <s:radio label="format" name="rptFmt" list="#{'pdf':'PDF'}" value="pdf" />
 </td>

</TR>

</TABLE>

</s:form>

</body>

</html>

Deployment Descriptor File
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>/Student.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>

</filter-mapping>


</web-app>

i am putting .jrxml file also .you can check and change according to your need using Ireport Tool :
<?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="StudentReport" pageWidth="500" pageHeight="600" columnWidth="450" leftMargin="5" rightMargin="5" topMargin="10" bottomMargin="1" uuid="71627f29-0436-4965-9e9b-c02d851e0893">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<style name="Arial" isDefault="true" fontName="Arial" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="Helvetica" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
<parameter name="Title" class="java.lang.String"/>
<parameter name="studid" class="java.lang.Integer"/>
<queryString>
<![CDATA[select id,name,college from student]]>
</queryString>
<field name="id" class="java.lang.String"/>
<field name="name" class="java.lang.String"/>
<field name="college" class="java.lang.String"/>
<title>
<band height="50" splitType="Stretch">
<textField isBlankWhenNull="true">
<reportElement style="Arial" x="40" y="0" width="370" height="30" uuid="aab52a34-7a15-413b-812b-0f5413d160cf"/>
<textElement textAlignment="Center">
<font size="22"/>
</textElement>
<textFieldExpression><![CDATA[$P{Title}]]></textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height="20" splitType="Stretch">
<textField>
<reportElement style="Arial" mode="Opaque" x="0" y="5" width="490" height="15" forecolor="#999999" backcolor="#777765" uuid="221943d8-6682-4b54-9096-de22d99fde6a"/>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA["Student Details "]]></textFieldExpression>
</textField>
</band>
</pageHeader>
<columnHeader>
<band height="20" splitType="Stretch">
<staticText>
<reportElement style="Arial" mode="Opaque" x="0" y="4" width="170" height="15" backcolor="#e3d9b4" uuid="4f05471d-ee17-42bc-afc7-4e474112b80f"/>
<textElement textAlignment="Left"/>
<text><![CDATA[ID]]></text>
</staticText>
<staticText>
<reportElement style="Arial" positionType="Float" mode="Opaque" x="170" y="4" width="170" height="15" backcolor="#e3d9b4" uuid="eb3e1f67-d402-432f-9faa-4174561d41cd"/>
<text><![CDATA[Name]]></text>
</staticText>
<staticText>
<reportElement style="Arial" positionType="Float" mode="Opaque" x="340" y="4" width="150" height="15" backcolor="#CBB453" uuid="ed2ace5c-9d4f-4c2d-baa9-c3a304949b60"/>
<text><![CDATA[College]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="4" width="170" height="15" uuid="818a285b-f0a1-42a0-95e5-04e630bf965e"/>
<textElement textAlignment="Left"/>
<textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
<reportElement positionType="Float" x="170" y="4" width="170" height="15" uuid="8d258287-9e74-44d6-9756-a5dfe7b98c25"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
<reportElement positionType="Float" x="340" y="4" width="150" height="15" uuid="cb56f92e-f5ab-4510-891b-8c2d8f864f33"/>
<textFieldExpression><![CDATA[$F{college}]]></textFieldExpression>
</textField>
</band>
</detail>
<pageFooter>
<band height="40" splitType="Stretch">
<textField>
<reportElement x="200" y="20" width="85" height="15" uuid="a22dda99-774c-497f-9295-fe2a487b7373"/>
<textElement textAlignment="Right"/>
<textFieldExpression><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
</textField>
<textField evaluationTime="Report">
<reportElement x="285" y="20" width="75" height="15" uuid="51a9c0af-8bd0-447e-a492-ef0e7df1fdd8"/>
<textElement textAlignment="Left"/>
<textFieldExpression><![CDATA[" of " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
</textField>
</band>
</pageFooter>
<summary>
<band height="35" splitType="Stretch">
<textField isStretchWithOverflow="true">
<reportElement style="Arial" x="175" y="20" width="165" height="15" uuid="87b3c116-0ea9-4bcc-b3f4-9cbb1a5f5e2b"/>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA["Total Number of Students : " +
String.valueOf($V{REPORT_COUNT})]]></textFieldExpression>
</textField>
</band>
</summary>
</jasperReport>


snapshot of application :



Any Suggetion will be appreciated.Thanks for reading this article.
For any Query get in touch with me on npjava90@gmail.com









Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...