整合Struts2+JasperReport Web報表應用示例

 

整合Struts2+JasperReport Web報表應用示例

 

JasperReports作爲一種優秀且開源的報表引擎,不利用太可惜了。同時,藉助開源的JasperReports模板設計利器iReports,可以可視化的設計報表模板。基於Web的報表在很多項目中都是需要的。而隨着Struts2的流行,就應該研究一下在Struts2下如何利用JasperReports進行報表輸出。本示例比較簡單,採用的數據源即爲JavaBean,而沒有采用複雜的數據庫,其實原理是一樣的。只是傳遞給JasperReports的參數隨着連接方式的變化而略加修改而已。

準備工作

所使用的類庫及Jar包如下圖所示:


1.使用的Jar

開發環境:MyEclipse5.5+Eclipse3.2+JDK5.0+Tomcat5.5+Struts 2.0.6。當然,本該所提供的源代碼下載中沒有提供相關的lib,因爲文件大太,如果需要,請留下email

源代碼下載:Struts2AndJasperReport.rar

設計報表模板

本例中採用JavaBean作爲數據源,用於顯示People對象的一些基本屬性,如所在序號、城市、姓名、地址,並對同一城市的人員進行彙總小結顯示。

至於如何在iReports中設計模板文件,請在網上參考其它文檔。這裏不再詳細解讀,或有時間俺再另寫文章來具體講解如何在iReports中設計報表模板。WebRoot/jasper/jasper_template.jrxml代碼如下:

<?xml version="1.0" encoding="UTF-8"  ?>
<!-- Created with iReport - A designer for JasperReports -->
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport
         
name="jasper_template"
         columnCount
="1"
         printOrder
="Vertical"
         orientation
="Portrait"
         pageWidth
="595"
         pageHeight
="842"
         columnWidth
="535"
         columnSpacing
="0"
         leftMargin
="30"
         rightMargin
="30"
         topMargin
="20"
         bottomMargin
="20"
         whenNoDataType
="NoPages"
         isTitleNewPage
="false"
         isSummaryNewPage
="false">
    
<property name="ireport.scriptlethandling" value="0" />
    
<property name="ireport.encoding" value="UTF-8" />
    
<import value="java.util.*" />
    
<import value="net.sf.jasperreports.engine.*" />
    
<import value="net.sf.jasperreports.engine.data.*" />

    
<parameter name="rptMan" isForPrompting="false" class="java.lang.String">
        
<defaultValueExpression ><![CDATA["sterning"]]></defaultValueExpression>
    
</parameter>
    
<parameter name="rptDate" isForPrompting="false" class="java.lang.String">
        
<defaultValueExpression ><![CDATA["2008-01-12"]]></defaultValueExpression>
    
</parameter>

    
<field name="city" class="java.lang.String">
        
<fieldDescription><![CDATA[city]]></fieldDescription>
    
</field>
    
<field name="street" class="java.lang.String">
        
<fieldDescription><![CDATA[street]]></fieldDescription>
    
</field>
    
<field name="id" class="java.lang.Integer">
        
<fieldDescription><![CDATA[id]]></fieldDescription>
    
</field>
    
<field name="name" class="java.lang.String">
        
<fieldDescription><![CDATA[name]]></fieldDescription>
    
</field>

    
<variable name="CityNumber" class="java.lang.Integer" resetType="Group" resetGroup="CityGroup" calculation="Sum">
        
<initialValueExpression><![CDATA[($V{CityNumber} != null)?(new Integer($V{CityNumber}.intValue() + 1)):(new Integer(1))]]></initialValueExpression>
    
</variable>
    
<variable name="AllCity" class="java.lang.Integer" resetType="Report" calculation="Sum">
        
<initialValueExpression><![CDATA[($V{AllCity} != null)?(new Integer($V{AllCity}.intValue() + 1)):(new Integer(1))]]></initialValueExpression>
    
</variable>

        
<group  name="CityGroup" >
            
<groupExpression><![CDATA[$F{city}]]></groupExpression>
            
<groupHeader>
            
<band height="0"  isSplitAllowed="true" >
            
</band>
            
</groupHeader>
            
<groupFooter>
            
<band height="37"  isSplitAllowed="true" >
                
<staticText>
                    
<reportElement
                        
x="98"
                        y
="5"
                        width
="51"
                        height
="25"
                        key
="staticText-8"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="14" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<text><![CDATA[灝忚錛歖]></text>
                </staticText>
                <textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None"  hyperlinkTarget="Self" >
                    <reportElement
                        x="149"
                        y="5"
                        width="34"
                        height="25"
                        key="textField-7"/>
                    <box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    <textElement>
                        <font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="14" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    </textElement>
                <textFieldExpression   class="java.lang.Integer"><![CDATA[$V{CityGroup_COUNT}
]]></textFieldExpression>
                
</textField>
                
<line direction="TopDown">
                    
<reportElement
                        
x="-30"
                        y
="36"
                        width
="593"
                        height
="0"
                        key
="line-5"/>
                    
<graphicElement stretchType="NoStretch"/>
                
</line>
            
</band>
            
</groupFooter>
        
</group>
        
<background>
            
<band height="0"  isSplitAllowed="true" >
            
</band>
        
</background>
        
<title>
            
<band height="62"  isSplitAllowed="true" >
                
<staticText>
                    
<reportElement
                        
x="20"
                        y
="0"
                        width
="484"
                        height
="57"
                        forecolor
="#FF0033"
                        key
="staticText-1"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement textAlignment="Center">
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="36" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<text><![CDATA[Struts2+JasperReports紺轟緥]]></text>
                
</staticText>
                
<line direction="TopDown">
                    
<reportElement
                        
x="-30"
                        y
="61"
                        width
="594"
                        height
="0"
                        key
="line-4"/>
                    
<graphicElement stretchType="NoStretch"/>
                
</line>
            
</band>
        
</title>
        
<pageHeader>
            
<band height="13"  isSplitAllowed="true" >
                
<line direction="TopDown">
                    
<reportElement
                        
x="-29"
                        y
="12"
                        width
="592"
                        height
="0"
                        key
="line-3"/>
                    
<graphicElement stretchType="NoStretch"/>
                
</line>
            
</band>
        
</pageHeader>
        
<columnHeader>
            
<band height="45"  isSplitAllowed="true" >
                
<staticText>
                    
<reportElement
                        
x="13"
                        y
="5"
                        width
="62"
                        height
="33"
                        key
="staticText-2"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="24" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<text><![CDATA[搴忓彿]]></text>
                
</staticText>
                
<staticText>
                    
<reportElement
                        
x="98"
                        y
="5"
                        width
="62"
                        height
="33"
                        key
="staticText-3"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="24" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<text><![CDATA[鍩庡競]]></text>
                
</staticText>
                
<staticText>
                    
<reportElement
                        
x="212"
                        y
="5"
                        width
="62"
                        height
="33"
                        key
="staticText-4"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="24" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<text><![CDATA[濮撳悕]]></text>
                
</staticText>
                
<staticText>
                    
<reportElement
                        
x="331"
                        y
="5"
                        width
="62"
                        height
="33"
                        key
="staticText-5"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="24" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<text><![CDATA[浣忓潃]]></text>
                
</staticText>
                
<line direction="TopDown">
                    
<reportElement
                        
x="-30"
                        y
="43"
                        width
="596"
                        height
="0"
                        key
="line-2"/>
                    
<graphicElement stretchType="NoStretch"/>
                
</line>
            
</band>
        
</columnHeader>
        
<detail>
            
<band height="43"  isSplitAllowed="true" >
                
<textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None"  hyperlinkTarget="Self" >
                    
<reportElement
                        
x="13"
                        y
="7"
                        width
="62"
                        height
="30"
                        key
="textField-1"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="14" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<textFieldExpression   class="java.lang.Integer"><![CDATA[$F{id}]]></textFieldExpression>
                
</textField>
                
<textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None"  hyperlinkTarget="Self" >
                    
<reportElement
                        
x="98"
                        y
="7"
                        width
="105"
                        height
="29"
                        key
="textField-2"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="14" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<textFieldExpression   class="java.lang.String"><![CDATA[$F{city}]]></textFieldExpression>
                
</textField>
                
<textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None"  hyperlinkTarget="Self" >
                    
<reportElement
                        
x="212"
                        y
="8"
                        width
="100"
                        height
="28"
                        key
="textField-3"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="14" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<textFieldExpression   class="java.lang.String"><![CDATA[$F{name}]]></textFieldExpression>
                
</textField>
                
<textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None"  hyperlinkTarget="Self" >
                    
<reportElement
                        
x="331"
                        y
="7"
                        width
="111"
                        height
="30"
                        key
="textField-4"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="14" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<textFieldExpression   class="java.lang.String"><![CDATA[$F{street}]]></textFieldExpression>
                
</textField>
                
<line direction="TopDown">
                    
<reportElement
                        
x="-30"
                        y
="37"
                        width
="593"
                        height
="0"
                        key
="line-1"/>
                    
<graphicElement stretchType="NoStretch"/>
                
</line>
            
</band>
        
</detail>
        
<columnFooter>
            
<band height="37"  isSplitAllowed="true" >
            
</band>
        
</columnFooter>
        
<pageFooter>
            
<band height="50"  isSplitAllowed="true" >
                
<textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Now" hyperlinkType="None"  hyperlinkTarget="Self" >
                    
<reportElement
                        
x="98"
                        y
="18"
                        width
="138"
                        height
="23"
                        key
="textField-8"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement textAlignment="Right">
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="12" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<textFieldExpression   class="java.lang.String"><![CDATA["欏墊暟 " + String.valueOf($V{PAGE_NUMBER}) + " of"]]></textFieldExpression>
                
</textField>
                
<textField isStretchWithOverflow="false" isBlankWhenNull="false" evaluationTime="Report" hyperlinkType="None"  hyperlinkTarget="Self" >
                    
<reportElement
                        
x="239"
                        y
="18"
                        width
="83"
                        height
="23"
                        key
="textField-9"/>
                    
<box topBorder="None" topBorderColor="#000000" leftBorder="None" leftBorderColor="#000000" rightBorder="None" rightBorderColor="#000000" bottomBorder="None" bottomBorderColor="#000000"/>
                    
<textElement>
                        
<font fontName="瀹嬩綋" pdfFontName="STSong-Light" size="12" isPdfEmbedded ="true" pdfEncoding ="UniGB-UCS2-H"/>
                    
</textElement>
                
<textFieldExpression   class="java.lang.String"><![CDATA[" " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
                
</textField>
            
</band>
        
</pageFooter>
        
<lastPageFooter>
            
<band height="50"  isSplitAllowed="true" >
            
</band>
        
</lastPageFooter>
        
<summary>
            
<band height="0"  isSplitAllowed="true" >
            
</band>
        
</summary>
</jasperReport>
 

這裏需要說明的是,由於俺們中國的中文比較特殊,由此在PDF中顯示的時候,需要一些額外的Jar包字體來支持。因此需要下載iTextAsian.jar包,此包專門用於顯示亞洲的字符。

 

設計JavaBean

 

由本例中沒有使用數據庫,而是使用JavaBean作爲JRDataSource,來傳遞給JasperReports作爲數據源,因此只需要設計JavaBean/src/com/sterning/PeopleBean.java的代碼很簡單,只在字個字段:cityidnamestreet,代碼如下所示:

package com.sterning;

public class PeopleBean
{
    
private String city = null;
    
private Integer id = null;
    
private String name = null;
    
private String street = null;

    
public PeopleBean(
        String pcity,
        Integer pid,
        String pname,
        String pstreet
        )
    
{
        city 
= pcity;
        id 
= pid;
        name 
= pname;
        street 
= pstreet;
    }


    
public PeopleBean getMe()
    
{
        
return this;
    }


    
public String getCity()
    
{
        
return city;
    }


    
public Integer getId()
    
{
        
return id;
    }


    
public String getName()
    
{
        
return name;
    }


    
public String getStreet()
    
{
        
return street;
    }

}


 

編譯模板

其實表面上說是填充數據,其實就是填充一個List。具體的工具都是交給我們的JasperReports去完成。JasperReports要完成數據的填充工作,要經歷將編譯(將模板文件.jrxml編譯成.jasper文件)、加載(加載.jasper文件)、填充(從數據源中取得數據並填充到.jasper二進制文件中)三大步驟。src/com/sterning/JasperAction.java,其代碼如下所示:

package com.sterning;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import net.sf.jasperreports.engine.JasperCompileManager;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class JasperAction extends ActionSupport {
    
private static final long serialVersionUID = 1L;

    
private List<PeopleBean> myList;

    
public String execute() throws Exception {
        
//添加數據
        PeopleBean p1=new PeopleBean("長沙"new Integer(9), "李化""天灑路");
        PeopleBean p2
=new PeopleBean("長沙"new Integer(22), "王小樣""呆小路564");
        PeopleBean p3
=new PeopleBean("南昌"new Integer(23), "王奸可""小順路");
        PeopleBean p4
=new PeopleBean("南昌"new Integer(32), "李灑""順濉路");
        PeopleBean p5
=new PeopleBean("武漢"new Integer(39), "張中尖""天灑路");
        PeopleBean p6
=new PeopleBean("武漢"new Integer(35), "陳主寧""天河路564");
        myList 
= new ArrayList<PeopleBean>();
        myList.add(p1);
        myList.add(p2);
        myList.add(p3);
        myList.add(p4);
        myList.add(p5);
        myList.add(p6);

        
try {
            String reportSource;
            reportSource 
= ServletActionContext.getServletContext()
                    .getRealPath(
"/jasper/jasper_template.jrxml");
            File parent 
= new File(reportSource).getParentFile();
            
//將.jrxml模板文件編譯成爲.jasper文件,當然,其文件名可以指定,如果沒指定,則與.jrxml文件名一樣.只是後綴不同而已
            JasperCompileManager.compileReportToFile(reportSource, new File(
                    parent, 
"compiled_jasper_template.jasper")
                    .getAbsolutePath());
        }
 catch (Exception e) {
            e.printStackTrace();
            
return ERROR;
        }

        
return SUCCESS;
    }


    
public List getMyList() {
        
return myList;
    }

}


 

配置Struts2文件

前面這些工作都是爲JasperReports而作的。接下來就是將JasperReports集成到Struts2中。

1.  Web.xml

首先是Web.xml。這個文件配置比較簡單,也比較常規,沒什麼好說,代碼如下WebRoot/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
>
    
<filter>
        
<filter-name>struts2</filter-name>
        
<filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        
</filter-class>
        
<init-param>
            
<param-name>config</param-name>
            
<param-value>
                struts-default.xml,struts-plugin.xml,struts.xml
            
</param-value>
        
</init-param>
    
</filter>
    
<filter-mapping>
        
<filter-name>struts2</filter-name>
        
<url-pattern>/*</url-pattern>
    
</filter-mapping>

    
<!-- The Welcome File List -->
    
<welcome-file-list>
        
<welcome-file>index.jsp</welcome-file>
    
</welcome-file-list>
</web-app>

 

2.  struts.xml

按理說struts.xml配置文件應該更加簡單,但這裏由於集成了JasperReports,所以看上去要複雜一點。先來看代碼:src/ 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>
    
<package name="default"
        extends
="struts-default,jasperreports-default">
        
<action name="PDF" class="com.sterning.JasperAction">
            
<result name="success" type="jasper">
                
<param name="location">
                    /jasper/compiled_jasper_template.jasper
                
</param>
                
<param name="dataSource">myList</param>
                
<param name="format">PDF</param>
            
</result>
        
</action>
        
<action name="HTML" class="com.sterning.JasperAction">
            
<result name="success" type="jasper">
                
<param name="location">
                    /jasper/compiled_jasper_template.jasper
                
</param>
                
<param name="dataSource">myList</param>
                
<param name="format">HTML</param>
            
</result>
        
</action>
        
<action name="XML" class="com.sterning.JasperAction">
            
<result name="success" type="jasper">
                
<param name="location">
                    /jasper/compiled_jasper_template.jasper
                
</param>
                
<param name="dataSource">myList</param>
                
<param name="format">XML</param>
            
</result>
        
</action>
        
<action name="CSV" class="com.sterning.JasperAction">
            
<result name="success" type="jasper">
                
<param name="location">
                    /jasper/compiled_jasper_template.jasper
                
</param>
                
<param name="dataSource">myList</param>
                
<param name="format">CSV</param>
            
</result>
        
</action>
        
<action name="XLS" class="com.sterning.JasperAction">
            
<result name="success" type="jasper">
                
<param name="location">
                    /jasper/compiled_jasper_template.jasper
                
</param>
                
<param name="dataSource">myList</param>
                
<param name="format">XLS</param>
            
</result>
        
</action>
    
</package>
</struts>
 

這裏,當調用JasperActionexecute()方法成功後,返回後,可見有三個參數:location告訴JasperReports數據填充類二進制的.jasper文件的位置,dataSource指明使用什麼數據源,format指明報表輸出的格式。


 

頁面文件

Index.jsp的代碼非常的簡單,如下:

<%@ page language="java" pageEncoding="GB2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    
<head>
        
<title>Struts2+ JasperReports 使用示例</title>
    
</head>
    
<body>
        
<href="HTML.action">HTML</a>
        
<br>
        
<href="PDF.action">PDF</a>
        
<br>
        
<href="XML.action">XML</a>
        
<br>
        
<href="CSV.action">CSV</a>
        
<br>
        
<href="XLS.action">XLS</a>
    
</body>
</html>

 

運行效果

1HTML格式

2.HTML格式

2PDF格式


3.PDF格式

3XML格式


4.XML格式

4Excel格式


5.Excel格式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章