繁体   English   中英

如何将连接和参数传递给struts2中的jasper报告?

[英]how to pass connections and parameter to jasper reports in struts2?

我想将连接和参数传递给jasper报告。 但是我得到空白的pdf文件。

这是我使用的代码,但显示空白的pdf文件。

这是我的struts.xml文件,它正在调用操作来生成报告文件。 同样在此文件中,我需要对con的描述。 如何运作?

<package name="reports" namespace="/reports" extends="jasperreports-default">
    <action name="getGuestDetails" class="com.hms.admin.report.GuestDetailReport">
         <result name="success" type="jasper">
            <param name="location">jsp/admin/report/GuestReport.jasper</param>
            <param name="connection">con</param>
            <param name="format">PDF</param>
            <param name="exportParameters">params</param>
        </result>
    </action>
</package>

这是我的动作课。 在此类中,使用mysql连接。

package com.hms.admin.report;

import com.hms.util.SetupDB;
import com.opensymphony.xwork2.ActionSupport;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import org.apache.struts2.ServletActionContext;

public class GuestDetailReport  extends ActionSupport{
    private String gname;
    public InputStream inputStream;

    public String getGname() {
        return gname;
    }
    public void setGname(String gname) {
        this.gname = gname;
    }

    @Override
    public String execute()throws Exception{
        try {
            Connection con=SetupDB.getConnection();
            String str = ServletActionContext.getServletContext().getRealPath("/jsp/admin/report/GuestReport.jrxml");
            JasperDesign jd=JRXmlLoader.load(str);        
            Map parameters = new HashMap();
            parameters.put("guestname", gname);
            JasperReport jr = JasperCompileManager.compileReport(jd);
            JasperPrint jp=JasperFillManager.fillReport(jr, parameters, con);
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,  ServletActionContext.getServletContext().getRealPath("/jsp/admin/report/GuestReport.pdf"));
            exporter.exportReport();
            File file = new File(ServletActionContext.getServletContext().getRealPath("/jsp/admin/report/GuestReport.pdf"));  
            inputStream = new DataInputStream( new FileInputStream(file));

            return SUCCESS;
        } catch (Exception e) {
            System.out.println("Exception in execute in GuestReport class");
            e.printStackTrace();
        }
        return SUCCESS;
    }
}

这是GuestReport.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="null" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="80e569cf-7fbf-42bc-bdc6-3e484f303e8f">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<style name="Title" fontName="Arial" fontSize="26" isBold="true" pdfFontName="Helvetica-Bold"/>
<style name="SubTitle" forecolor="#666666" fontName="Arial" fontSize="18"/>
<style name="Column header" forecolor="#666666" fontName="Arial" fontSize="12" isBold="true"/>
<style name="Detail" fontName="Arial" fontSize="12"/>
<parameter name="guestname" class="java.lang.String">
    <defaultValueExpression><![CDATA[]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[SELECT guestid, guestname, fname, address, country, phoneno, mobileno, emailid, gender, company, addedon from guesttable where guestname=$P{guestname}]]>
</queryString>
<field name="guestid" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="guestname" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="fname" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="address" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="country" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="phoneno" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="mobileno" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="emailid" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="gender" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="company" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="addedon" class="java.sql.Date">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<background>
    <band splitType="Stretch"/>
</background>
<title>
    <band height="57" splitType="Stretch">
        <staticText>
            <reportElement uuid="c01df362-f765-4b72-980e-ca6678010fe0" style="Title" x="0" y="1" width="552" height="55" forecolor="#006600"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">
                <font fontName="Cambria" size="36" isUnderline="true"/>
            </textElement>
            <text><![CDATA[Radisson]]></text>
        </staticText>
    </band>
</title>
<columnHeader>
    <band height="37" splitType="Stretch">
        <line>
            <reportElement uuid="6d1a04ea-d848-4665-9d1d-a395f4a7f66d" positionType="FixRelativeToBottom" x="0" y="35" width="555" height="1"/>
            <graphicElement>
                <pen lineWidth="0.5" lineColor="#999999"/>
            </graphicElement>
        </line>
        <staticText>
            <reportElement uuid="c01df362-f765-4b72-980e-ca6678010fe1" x="0" y="15" width="110" height="20" forecolor="#006600"/>
            <textElement verticalAlignment="Middle">
                <font fontName="Cambria" size="16"/>
            </textElement>
            <text><![CDATA[Guest's Details]]></text>
        </staticText>
    </band>
</columnHeader>
<detail>
    <band height="150" splitType="Stretch">
        <staticText>
            <reportElement uuid="4c5db3f1-4205-4443-9076-61322115f438" style="Column header" x="0" y="39" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Guest ID :]]></text>
        </staticText>
        <textField>
            <reportElement uuid="505e5e3e-a5a4-4f69-aebb-58593675ad0e" style="Detail" x="138" y="39" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{guestid}]]></textFieldExpression>
        </textField>
        <staticText>
            <reportElement uuid="e7afe77f-0195-4af3-b012-4fc6c28bbece" style="Column header" x="0" y="55" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Guest Name   :]]></text>
        </staticText>
        <textField>
            <reportElement uuid="4994add0-1f23-48da-812e-50dced411862" style="Detail" x="138" y="55" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{guestname}]]></textFieldExpression>
        </textField>
        <staticText>
            <reportElement uuid="781ad85c-e603-4f00-8755-4e18a9956a8c" style="Column header" x="0" y="71" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Father's Name    :]]></text>
        </staticText>
        <textField>
            <reportElement uuid="ec4ef88f-3ca1-4b2d-8d0c-bcc46fec09ce" style="Detail" x="138" y="71" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{fname}]]></textFieldExpression>
        </textField>
        <staticText>
            <reportElement uuid="0d560702-cbf4-4876-af95-cc8c382a05a2" style="Column header" x="0" y="87" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Address  :]]></text>
        </staticText>
        <textField>
            <reportElement uuid="c8330789-ccf0-4074-bbd8-153857a922c8" style="Detail" x="138" y="87" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{address}]]></textFieldExpression>
        </textField>
        <staticText>
            <reportElement uuid="ac8f2a0e-78d0-40dc-8216-0bb5e939e4c9" style="Column header" x="0" y="103" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Country  :]]></text>
        </staticText>
        <textField>
            <reportElement uuid="fee7669f-9dfb-4eab-9c5a-dfe6eee68eac" style="Detail" x="138" y="103" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{country}]]></textFieldExpression>
        </textField>
        <staticText>
            <reportElement uuid="ef5eaa35-cee7-47d1-9e9e-9a4ceb67d51f" style="Column header" x="0" y="119" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Phone        :]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="bfb35396-3729-4b81-b413-978f86533935" style="Column header" x="0" y="135" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Mobile       :]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="20ab5f69-681e-49b7-b751-522ce1d2b831" style="Column header" x="279" y="39" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Email Id :]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="ec6a9bb6-224d-4edd-ad6c-e8b0bf13c4f2" style="Column header" x="279" y="55" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Gender   :]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="4182f20d-32b7-4069-a60d-021e3af9ca4f" style="Column header" x="279" y="71" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Company  :]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="3b1378ea-bcd2-49c1-a1cf-1d7ae35b120f" style="Column header" x="279" y="87" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <text><![CDATA[Added On :]]></text>
        </staticText>
        <textField>
            <reportElement uuid="a44af4a4-91ac-467d-9f4f-482df18fd656" style="Detail" x="138" y="119" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{phoneno}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="7cfb0396-0f9c-4839-9588-1313c5cc4880" style="Detail" x="138" y="135" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{mobileno}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="e107192c-a97b-4b5f-9108-eb5c5fdd72de" style="Detail" x="417" y="87" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{addedon}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="dcce2af8-2112-4d00-a28b-dc315c054b81" style="Detail" x="417" y="71" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{company}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="4cc56fee-ce1e-4ca3-95b4-e37578afbff7" style="Detail" x="417" y="55" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{gender}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="bd9f5ae6-9b4c-4af2-a050-e8b4e71ea4b4" style="Detail" x="417" y="39" width="138" height="15"/>
            <textElement>
                <font fontName="Cambria"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{emailid}]]></textFieldExpression>
        </textField>
    </band>
</detail>
<pageFooter>
    <band height="20" splitType="Stretch">
        <textField>
            <reportElement uuid="498e12bf-d73e-4d0c-9048-d879bb99f24b" style="Column header" x="433" y="0" width="80" height="20"/>
            <textElement textAlignment="Right">
                <font size="10" isBold="false"/>
            </textElement>
            <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
        </textField>
        <textField evaluationTime="Report">
            <reportElement uuid="5a4642a4-4eb7-4a4d-b99c-4576af6dc152" style="Column header" x="513" y="0" width="40" height="20"/>
            <textElement>
                <font size="10" isBold="false"/>
            </textElement>
            <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
        </textField>
        <textField pattern="EEEEE dd MMMMM yyyy">
            <reportElement uuid="e74731ca-f472-45a9-9c51-11e03e6c97bf" style="Column header" x="0" y="0" width="197" height="20"/>
            <textElement>
                <font size="10" isBold="false"/>
            </textElement>
            <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
        </textField>
    </band>
</pageFooter>
<summary>
    <band splitType="Stretch"/>
</summary>

您可以通过以下方式将连接对象作为单独的参数发送。

JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStreamObj);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, con);

我认为这很有用

我正在分享完整的代码。 检查一次。

public static String jasperReports(Connection con, String reportLocation, Map parameters, String fileName, String fileType, String jasperFileName) {
        String strReturn = "0";
        FileInputStream fis = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            HttpServletRequest request = ServletActionContext.getRequest();
            HttpSession session = request.getSession();
            Locale currentLocale = new Locale("en", "US");
            ResourceBundle resourceBundle = ResourceBundle.getBundle("ResourceBundle.ReportsTabNames_"+DBVariables.ModuleNameFY, currentLocale);
            parameters.put("REPORT_RESOURCE_BUNDLE", resourceBundle);
            logger.info("AAAAa"+DBVariables.ModuleNameFY+" :: jasperReports::::::::Parameters::::"+parameters);
            String strLoginName = (String) session.getAttribute("UserName");
            String strFilePath = ServletActionContext.getServletContext().getRealPath("Repository") + "/" + strLoginName;
            boolean test = (new File(strFilePath)).exists();
            if (test) {
                File directory = new File(strFilePath);
                File[] files = directory.listFiles();
                for (File file : files) {
                    boolean str = file.isDirectory();
                    if (str) {
                        File[] children = file.listFiles();
                        for (File fileList : children) {
                            File[] children2 = fileList.listFiles();
                            for (File fileCount : children2) {
                                fileCount.delete();
                            }
                            fileList.delete();
                        }
                        file.delete();
                    } else if (!file.delete()) {
                        logger.error("AAAAa"+DBVariables.ModuleNameFY+" :: Failed to delete " + file);
                    }
                }
            }
            if (!test) {
                test = (new File(strFilePath)).mkdirs();
            }
            logger.info("AAAAa"+DBVariables.ModuleNameFY+" :: jasper file location::::::"+reportLocation + "\\" + jasperFileName + ".jasper");
            fis = new FileInputStream(reportLocation + "\\" + jasperFileName + ".jasper");
            bufferedInputStream = new BufferedInputStream(fis);
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, con);

            if (fileType.equalsIgnoreCase("PDF")) {
                File fileobj = new File(strFilePath + "/" + fileName + ".pdf");
                fileobj.deleteOnExit();
                JasperExportManager.exportReportToPdfFile(jasperPrint, strFilePath + "\\" + fileName + ".pdf");
            } else if (fileType.equalsIgnoreCase("XLS")) {
                File fileobj = new File(strFilePath + "/" + fileName + ".xls");
                fileobj.deleteOnExit();
                JRXlsExporter exporterXls = new JRXlsExporter();
                exporterXls.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporterXls.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
                exporterXls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);// False
                exporterXls.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
                exporterXls.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
                exporterXls.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFilePath + "\\" + fileName + ".xls");
                exporterXls.exportReport();
            } else if (fileType.equalsIgnoreCase("HTML")) {
                File fileobj = new File(strFilePath + "/" + fileName + ".html");
                fileobj.deleteOnExit();
                JRHtmlExporter htmlExporter = new JRHtmlExporter();
                htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                htmlExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFilePath + "\\" + fileName + ".html");
                htmlExporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
                htmlExporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
                htmlExporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);
                htmlExporter.exportReport();
            } else if (fileType.equalsIgnoreCase("DOCX")) {
                File fileobj = new File(strFilePath + "/" + fileName + ".docx");
                fileobj.deleteOnExit();
                JRDocxExporter docExporter = new JRDocxExporter();
                docExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                docExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFilePath + "\\" + fileName + ".docx");
                docExporter.exportReport();
            } else if (fileType.equalsIgnoreCase("ODT")) {
                File fileobj = new File(strFilePath + "/" + fileName + ".odt");
                fileobj.deleteOnExit();
                JROdtExporter odtExporter = new JROdtExporter();
                odtExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                odtExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFilePath + "\\" + fileName + ".odt");
                odtExporter.exportReport();
            } else if (fileType.equalsIgnoreCase("RTF")) {
                File fileobj = new File(strFilePath + "/" + fileName + ".rtf");
                fileobj.deleteOnExit();
                JRRtfExporter rtfExporter = new JRRtfExporter();
                rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                rtfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, strFilePath + "\\" + fileName + ".rtf");
                rtfExporter.exportReport();
            }
            strReturn = "0";
        } catch (JRException e) {
            logger.error("AAAAa"+DBVariables.ModuleNameFY+" :: jasperReports() ::JRException :: " + e.getMessage());
            strReturn = "-1";
        } catch (Exception e) {
            logger.error("AAAAa"+DBVariables.ModuleNameFY+" :: jasperReports() ::Exception :: " + e.getMessage());
            strReturn = "-1";
        } finally {
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                    bufferedInputStream = null;
                }
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
            } catch (Exception e) {
                logger.error("AAAAa"+DBVariables.ModuleNameFY+" :: jasperReports() ::Exception :: " + e.getMessage());
            }
            return strReturn;
        }
    }
Connection con=SetupDB.getConnection();

在GuestDetailReport类中使全局对象具有全局性,并创建它的getter / setter方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM