Thursday 18 September 2014

Struts 2 jasper report example

Apache Struts 2, another popular Java Model-View-Contraller (MVC) framework, combine of both successful WebWork and Struts 1.x web frameworks.

Jasper report is java based reporting tools. Struts2 provide jasper report plugins for ingratiation of report in your web application.Today we learn how to implement this in eclipse.

 1 . Create new Maven project in eclipse and select maven-archetype-webapp

 2. Fill Group Id, Artifact Id,package information then click finish.
3. after finish its show following structure.
4.open pom.xml and add struts2 and jasper report dependency.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.riddimablog</groupId>
    <artifactId>jasper_example</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>jasper_example Maven Webapp</name>
    <url>http://maven.apache.org</url>
   
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.16.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-jasperreports-plugin</artifactId>
            <version>2.3.16.3</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>5.5.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.7</version>
        </dependency>


    </dependencies>
    <build>
        <finalName>jasper_example</finalName>
    </build>
</project>

5.create new package  com.riddima.jasper in src/main/java folder.

6 . create User.java class in com.riddima.jasper package and write following code.
   package com.riddima.jasper;

public class User {
    private Long id;
    private String firstName = null;
    private String lastName = null;
    private String fatherName = null;
    private String address = null;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFatherName() {
        return fatherName;
    }

    public void setFatherName(String fatherName) {
        this.fatherName = fatherName;
    }

    public String getListDescription() {

        return lastName + "," + firstName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public User(String firstName, String lastName, String fatherName,
            String address) {
        // TODO Auto-generated constructor stub
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.fatherName = fatherName;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer("User Information \n");
        sb.append("First Name : " + firstName + "\n");
        sb.append("Last Name : " + lastName + "\n");
        sb.append("Father Name : " + fatherName + "\n");
        sb.append("Address : " + address + "\n");
        return sb.toString();
    }

}
7.Create JasperAction.java class in com.riddima.jasper folder and write following code.

package com.riddima.jasper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.struts2.StrutsStatics;

import net.sf.jasperreports.engine.JasperCompileManager;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


/**
 * @author :Riddima blog
 * @version $Id:
 */
public class JasperAction extends ActionSupport {
  
    private List<User> myList;
    private String format = "PDF";
    private String contentType = "application/pdf";
    private String fileName = "document.pdf";
    private String jasperfileName = "sample.jasper";
    private HashMap reportParams = new HashMap();
  
    public HashMap getReportParams() {
        return reportParams;
    }
    public void setReportParams(HashMap reportParams) {
        this.reportParams = reportParams;
    }
    public String getJasperfileName() {
        return jasperfileName;
    }
    public String getFormat() {
        return format;
    }
    public String execute() throws Exception {
        // dummy data create or feel free to change to data get in service class
        myList=new ArrayList<User>();
        User user1 =new User("Michael","Jackson","Joseph Jackson","Gary, Indiana, U.S.");
        User user2 =new User("Tom","Cruise","Thomas Cruise","Syracuse, New York, U.S.");
        myList.add(user1);
        myList.add(user2);
        /*//for service class
         *
        UserService service = new UserService();
        myList = service.getUsers();
        */
      
          // Normally we would provide a pre-compiled .jrxml file
        // or check to make sure we don't compile on every request.
        try {
            JasperCompileManager.compileReportToFile(
                    getApplicationPath()+"/jasper/sample.jrxml",
                    getApplicationPath()+"/jasper/sample.jasper");
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
      
      
      
        reportParams.put("userName", "admin");
        return SUCCESS;
    }
    public List<User> getMyList() {
        return myList;
    }
    public void setFormat(String format) {
        this.format = format;
        if ("XLS".equals(format)) {
            fileName = "document.html";
        }
    }
    public String getContentType() {
        if ("XLS".equals(format)) {
            contentType = "application/xls";
        } else if ("HTML".endsWith(format)) {
            contentType = "text/html";
        }
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    public String getFileName() {
        if ("XLS".equals(format)) {
            fileName = "document.xls";
        } else if ("HTML".endsWith(format)) {
            fileName = "document.html";
        }
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public void setMyList(List<User> myList) {
        this.myList = myList;
    }
  
    public String getApplicationPath() {
        return ((ServletContext)ActionContext.getContext().get(StrutsStatics.SERVLET_CONTEXT)).getRealPath("/");
    }
}


8.  jasper Report HTML format need some image file to view correct report.so create ImageAction.java class in com.riddima.jasper package. write following code


package com.riddima.jasper;

import java.awt.Dimension;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

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

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRImageRenderer;
import net.sf.jasperreports.engine.JRPrintImage;
import net.sf.jasperreports.engine.JRRenderable;
import net.sf.jasperreports.engine.JRWrappingSvgRenderer;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.util.JRTypeSniffer;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class ImageAction extends ActionSupport implements ServletRequestAware,
        ServletResponseAware, ApplicationAware, SessionAware, Preparable {
    private String contentType = "image/gif";
    private String imageName;

    private HttpServletRequest request;

    private InputStream fileInputStream;

    public void setServletRequest(HttpServletRequest arg0) {
        // TODO Auto-generated method stub
        this.request = arg0;

    }

    public void setServletResponse(HttpServletResponse arg0) {
        // TODO Auto-generated method stub

    }

    public void setSession(Map<String, Object> arg0) {
        // TODO Auto-generated method stub

    }

    public void prepare() throws Exception {
        // TODO Auto-generated method stub

    }

    public void setApplication(Map<String, Object> arg0) {
        // TODO Auto-generated method stub

    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        byte[] imageData = null;
        String imageMimeType = null;
        if ("px".equals(imageName)) {
            try {
                JRRenderable pxRenderer = JRImageRenderer
                        .getInstance("net/sf/jasperreports/engine/images/pixel.GIF");
                imageData = pxRenderer.getImageData();
            } catch (JRException e) {
                throw new ServletException(e);
            }
        } else {
            List jasperPrintList = BaseHttpServlet.getJasperPrintList(request);

            if (jasperPrintList == null) {
                throw new ServletException(
                        "No JasperPrint documents found on the HTTP session.");
            }

            JRPrintImage image = JRHtmlExporter.getImage(jasperPrintList,
                    imageName);

            JRRenderable renderer = image.getRenderer();
            if (renderer.getType() == JRRenderable.TYPE_SVG) {
                renderer = new JRWrappingSvgRenderer(renderer, new Dimension(
                        image.getWidth(), image.getHeight()),
                        image.getBackcolor());
            }

            imageMimeType = JRTypeSniffer.getImageMimeType(renderer
                    .getImageType());

            try {
                imageData = renderer.getImageData();
            } catch (JRException e) {
                throw new ServletException(e);
            }
        }

        fileInputStream = new ByteArrayInputStream(imageData);

        System.out.println();
        return SUCCESS;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public InputStream getFileInputStream() {
        return fileInputStream;
    }

}
9. src/main/resource folder create struts.xml file. write following mapping

<?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="true" />
    <constant name="struts.devMode" value="true" />

    <package name="riddima" namespace="/" extends="struts-default">
        <result-types>
            <result-type name="jasper"
                class="org.apache.struts2.views.jasperreports.JasperReportsResult"
                default="false" />
        </result-types>
        <action name="jasper" class="com.riddima.jasper.JasperAction">
            <result name="success" type="jasper">
                <param name="location">/jasper/${jasperfileName}</param>
                <param name="dataSource">myList</param>
                <param name="format">${format}</param>
                <param name="contentType">${contentType}</param>
                <param name="contentDisposition">filename=${fileName}</param>
                <param name="reportParameters">reportParams</param>
                <param name="exportParameters">exportParameters</param>
                <param name="imageServletUrl">/imageGet?imageName=</param>
            </result>
        </action>
        <action name="imageGet" class="com.riddima.jasper.ImageAction">
            <result name="success" type="stream">
                <param name="contentType">${format}</param>
                <param name="inputName">fileInputStream</param>
            </result>
        </action>

    </package>
</struts>
10. See jasper action have multiple param
           
  • location=> /jasper/${jasperfileName}:   jasperfileName parameter set dynamic in action class.in our case this value is sample.jasper.
  • dataSource=>myList  : jasper report datasource.
  • format=>${format}:jasper report output format in our case its value is pdf/xls/html.
  • contentType=>${contentType}:jasper  report content type
  • contentDisposition=>filename=${fileName}:jasper report file name
  • reportParameters=>reportParams: jasper report parameter value set in this map.
  • exportParameters=>exportParameters:jasper report export parameters value set in this map.
  • imageServletUrl=>/imageGet?imageName= :jasper report need some image for display report.
     
11 .src/main/webapps create jasper folder and create sample.jrxml file and write following code.

<?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="jasper_test" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30" uuid="05cdb2bc-eb7b-4d18-b711-a07b69e8040b">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <parameter name="userName" class="java.lang.String"/>
    <field name="firstName" class="java.lang.String"/>
    <field name="lastName" class="java.lang.String"/>
    <field name="fatherName" class="java.lang.String"/>
    <field name="address" class="java.lang.String"/>
    <title>
        <band height="50" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="180" height="15" forecolor="#FF3333" uuid="2f591c42-1eac-4513-b005-d4e2b8ff115f"/>
                <text><![CDATA[Struts 2 JasperReports Sample]]></text>
            </staticText>
            <staticText>
                <reportElement x="0" y="15" width="555" height="25" forecolor="#0000CC" uuid="94478d08-1c46-4f65-af34-7f35e9ea0765"/>
                <textElement textAlignment="Center">
                    <font size="18"/>
                </textElement>
                <text><![CDATA[User Information]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band height="20" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="111" height="20" forecolor="#000000" uuid="c886fa02-f49f-45af-8d58-2f310528488c"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5" lineColor="#000000"/>
                    <leftPen lineWidth="0.5" lineColor="#000000"/>
                    <bottomPen lineWidth="0.5" lineColor="#000000"/>
                    <rightPen lineWidth="0.5" lineColor="#000000"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[First Name]]></text>
            </staticText>
            <staticText>
                <reportElement x="111" y="0" width="111" height="20" forecolor="#000000" uuid="c91b3870-fd06-4902-8680-3b43fd92fd0b"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5" lineColor="#000000"/>
                    <leftPen lineWidth="0.5" lineColor="#000000"/>
                    <bottomPen lineWidth="0.5" lineColor="#000000"/>
                    <rightPen lineWidth="0.5" lineColor="#000000"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[Last Name]]></text>
            </staticText>
            <staticText>
                <reportElement x="222" y="0" width="111" height="20" forecolor="#000000" uuid="55336bbc-39ed-4c46-ae27-c4b55388df97"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5" lineColor="#000000"/>
                    <leftPen lineWidth="0.5" lineColor="#000000"/>
                    <bottomPen lineWidth="0.5" lineColor="#000000"/>
                    <rightPen lineWidth="0.5" lineColor="#000000"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[Father Name]]></text>
            </staticText>
            <staticText>
                <reportElement x="333" y="0" width="222" height="20" forecolor="#000000" uuid="51e63565-6de8-470d-adc8-a9ca1422f84f"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5" lineColor="#000000"/>
                    <leftPen lineWidth="0.5" lineColor="#000000"/>
                    <bottomPen lineWidth="0.5" lineColor="#000000"/>
                    <rightPen lineWidth="0.5" lineColor="#000000"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[Address]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="111" height="20" uuid="b9ecd8a2-1f68-4b84-93bc-debe4759dd98"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{firstName}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="111" y="0" width="111" height="20" uuid="51cfd5bb-16bd-448c-aa16-b49d4e969cbc"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{lastName}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="222" y="0" width="111" height="20" uuid="0314091a-0dae-4d98-bce7-2f6de313cadd"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{fatherName}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="333" y="0" width="222" height="20" uuid="4313acfb-17b4-40c7-a816-df919f0e57bb"/>
                <box>
                    <pen lineWidth="0.5"/>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement textAlignment="Center" verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$F{address}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="23" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="40" height="15" forecolor="#3333FF" uuid="56c63566-a73d-4111-bd94-1ada136abce6"/>
                <text><![CDATA[Page:]]></text>
            </staticText>
            <textField>
                <reportElement x="40" y="0" width="100" height="15" uuid="e0d09684-1b45-437a-87f1-54d685dcab79"/>
                <textFieldExpression><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="453" y="2" width="100" height="20" uuid="87785a25-993e-4072-85c0-16c8dca8f71f"/>
                <textElement verticalAlignment="Middle"/>
                <textFieldExpression><![CDATA[$P{userName}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="344" y="2" width="107" height="20" forecolor="#3333FF" uuid="b74fc49d-45a1-4651-ac67-cf89f8a65660"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font size="12"/>
                </textElement>
                <text><![CDATA[Generated By :]]></text>
            </staticText>
        </band>
    </pageFooter>
    <summary>
        <band splitType="Stretch"/>
    </summary>
</jasperReport>

12. open web.xml and add following code

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts2 Application</display-name>
     <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>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>





13. open index.jsp and add following code.

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
    <h2>
        <s:url action="jasper" var="pdfLink">

        </s:url>
        <s:url action="jasper" var="excelLink">
            <s:param name="format" value="'XLS'" />
        </s:url>
        <s:url action="jasper" var="htmlLink">
            <s:param name="format" value="'HTML'" />
        </s:url>

        <a href='<s:property value="#pdfLink" />'> PDF </a><br> <a
            href='<s:property value="#excelLink" />'> Excel </a><br> <a
            href='<s:property value="#htmlLink" />'> HTML </a>

    </h2>
</body>
</html>

14 . Run project and see output.





15. Github link