FeaturesPluginsDocs & SupportCommunityPartners

>> 更多 Visual Web Pack 文档

从 Web 应用程序中生成报告和 PDF

2007 年 5 月 [修订号:V5.5.1-1]    

当您需要从 Web 应用程序中生成报告、图表或 PDF 文件时,许多第三方产品(其中包括开放源代码的 JasperReports 框架)都可以帮助您完成此项任务。JasperReports 作为一种报告工具,可以输出 HTML、PDF、XLS、CSV 和 XML 格式的报告。本教程向您介绍如何将 JasperReports 框架集成到使用 NetBeans Visual Web Pack 构建的 Web 应用程序中。

在本教程中,您将创建一个 Web 应用程序,该应用程序可以显示并输出 Travel 数据库中的信息。通过该 Web 应用程序,您可以查看 HTML 格式或 PDF 格式的行程报告。

目录

创建 JasperReports 库
设置 JRXML 编辑环境
创建项目
设置报告资源
映射 JasperReports ImageServlet
添加报告生成逻辑
创建数据库查询
创建行程报告页
  此页面上的内容适用于 NetBeans Visual Web Pack 5.5 和 5.5.1

JavaServer Faces 组件/
Java EE 平台
使用 1.2/Java EE 5*
使用 1.1/J2EE 1.4
Travel 数据库 必需必需
BluePrints AJAX 组件库 不是必需的不是必需的

* 该教程发布时,只有 Sun Java System Application Server 支持 Java EE 5。

本教程是针对使用 Sun Java Application Server PE 9.0 Update Release 1 和 Tomcat 5.5.17 进行定制的。如果您使用的是其他服务器,请参考发行说明常见问题解答以了解已知问题和解决方法。有关支持的服务器和 Java EE 平台的详细信息,请参见发行说明

创建 JasperReports 库

构建项目之前,请使用 IDE 的库管理器添加 JasperReports Java 报告库以方便任何项目使用。
  1. 通过 http://www.jasperforge.org Web 站点下载 jasperreports-1.3.0-project.zip,然后对其进行解压缩。您必须首先在 JasperForge 站点中注册,然后才能下载此 zip 文件。

    注意:本教程使用的示例是 JasperReports 1.3.0 及其提供的关联 JAR 文件。如果您使用的是其他版本,则 JAR 库名称和版本号会有所不同。此外,要添加的 JAR 库列表也会有所不同。
  2. 在 IDE 中,从主菜单中选择“工具”>“库管理器”。
  3. 单击“新建库”,在“库名称”文本框中键入 JasperReports130,然后单击“确定”。
  4. 单击“添加 JAR/文件夹”,然后导航至解压缩 jasperreports-1.3.0-project.zip 文件所在的目录。
  5. 找到 dist 目录并选择 jasperreports-1.3.0.jar,然后按 Enter 键。
  6. 再次单击“添加 JAR/文件夹”,然后导航至 ../lib 目录(转到上一级目录,然后找到 lib 目录)。
  7. 按住 Ctrl 键的同时单击鼠标左键,以选择下列 JAR 文件,然后按 Enter 键。如果您使用的版本不是 1.3.0,请查阅 JasperForge Web 站点以确定要选择的 JAR 文件。

    • commons-beanutils-1.7.jar
    • commons-collections-2.1.jar
    • commons-digester-1.7.jar
    • commons-logging-1.0.2.jar
    • itext-1.3.1.jar
    对于使用 JasperReports 框架的 Web 应用程序来说,必须至少包含上述库文件。若要使用更高级的功能,您可能还需要添加其他库。例如,如果要使用子报告功能,则还需要添加 commons-javaflow-20060411.jar
  8. 请确保添加了上面 6 个库文件,如下图所示。

    图 1:显示 JasperReports130 库的“库管理器”窗口
    图 1:显示 JasperReports130 库的“库管理器”窗口
  9. 为了让 Java 编辑器能够使用 JavaReports Javadoc,请依次单击 "Javadoc" 标签和“添加 ZIP/文件夹”,然后导航至解压缩 jasperreports-1.3.0-project.zip 文件所在的目录,选择 dist/javadoc 子目录,然后按 Enter 键。
  10. (可选)如果要在调试会话期间步入 JasperReport 类,请依次单击“源”标签和“添加 JAR/文件夹”,然后导航至解压缩 jasperreports-1.3.0-project.zip 文件所在的目录,选择 src 子目录,然后按 Enter 键。
  11. 单击“确定”关闭库管理器。

设置 JRXML 编辑环境

您需要编写 XML 格式的 JavaReport 模板。为了让 IDE 编辑器能够将 JavaReport XML 文件 (JRXML) 识别为 XML 文件,请通过“选项”对话框,将 jrxml 添加到 XML 对象的“扩展名和 MIME 类型”属性中,如下图所示。

图 2:将 JRXML 文件与 XML 对象关联
图 2:将 JRXML 文件与 XML 对象关联
  1. 选择“工具”>“选项”以打开“选项”对话框。
  2. 单击“高级选项”。
  3. 依次展开“IDE 配置”、“系统”和“对象类型”,然后选择“XML 对象”(不是“XML 架构”)。
  4. 单击位于“扩展名和 MIME 类型”属性旁边的省略号 (...) 按钮,打开定制编辑器。
  5. 在“项”文本框中键入 jrxml,然后单击“添加”。
  6. 单击“确定”,然后关闭“选项”对话框。

创建项目

请完成以下步骤,以创建并设置项目。
  1. 在“运行环境”窗口中,展开“数据库”节点。
  2. 右键单击 Travel 数据库的 jdbc 节点,然后从弹出式菜单中选择“连接”。

    如果 Travel 数据库不可用,请参见 NetBeans Visual Web Pack 5.5 安装说明中的配置信息部分以了解相关信息。
  3. 在出现的“连接”对话框中,输入 travel 作为口令,然后选中“在此会话期间记住口令”复选框。
  4. 在 IDE 的主菜单中,选择“文件”>“新建项目”。
  5. 在新建项目向导中,从“类别”列表中选择 "Web",然后从“项目”列表中选择“Visual Web 应用程序”。
  6. 单击“下一步”。
  7. 将项目命名为 TravelReport
  8. 选择所需的服务器和 Java EE 版本,然后单击“完成”。

    将显示该项目,并且其初始页 (Page1) 在可视设计器中处于打开状态。

    请注意,如果要使用的服务器不属于 Sun Java System Application Server,则该服务器必须可以使用此数据库驱动程序。有关详细信息,请参见安装指南中的 Visual Web 项目配置部分。

  9. 在“项目”窗口中,右键单击 "TravelReport" >“库”,然后选择“添加库”。
  10. 在“添加库”窗口中,选择 "JasperReports130"(如下图所示),然后单击“添加库”。

    图 3:添加 JasperReports126 库
    图 3:添加 JasperReports130 库

设置报告资源

在本部分,您将添加一个图像目录,然后将公司徽标放在该目录中。接下来,您将添加一个行程报告的 JRXML 模板,然后修改项目的生成文件以将 JRXML 模板编译为 Jasper 二进制报告模板。

JRXML 模板将生成一个报告,如下图所示。

图 4:行程报告
图 4:行程报告
  1. 在“项目”窗口中,展开“Web 页”。
  2. 右键单击 "resources" 节点,然后选择“新建”>“文件夹”。
  3. 在“文件夹名称”文本框中键入 images,然后按 Enter 键。
  4. 右键单击下面的图像,然后使用浏览器命令将图像保存在磁盘中。请将图像保存在 path-to-web-project/TravelReport/web/resosurces/images 文件夹中。

    图 5:公司徽标
    图 5:公司徽标
  5. 单击“文件”标题(位于“项目”标题的旁边)以查看“文件”窗口。
  6. 在“文件”窗口中,展开 "TravelReport"。
  7. 右键单击 "src" 节点,然后选择“新建”>“文件夹”。
  8. 在“文件夹名称”文本框中键入 reports
  9. 请确保“父文件夹”被设置为 src,然后按 Enter 键。
  10. 在“文件”窗口中,右键单击 "TravelReport",然后选择“属性”。
  11. 在“类别”窗格中,选择“源”。
  12. 单击位于“源包文件夹”列表右侧的“添加文件夹”按钮。
  13. 导航至 src 文件夹,选择 "reports",然后单击“打开”。
  14. 在 src/reports 行的“标签”文本框中,将值更改为 JasperReports Definition,然后按 Enter 键。

    如果未按 Enter 键,则 IDE 将不会保存所做的更改。
  15. 单击“确定”。
  16. 单击“项目”标题,您会注意到出现了一个新的 "JasperReports Definition" 节点,它包含一个 <缺省包> 子节点。

    接下来,您需要将一份报告定义放在此缺省包中。稍后,您需要修改生成脚本以便将此文件夹的报告定义编译到 build/web/WEB-INF/reports 文件夹中,ApplicationBean1 中的运行时代码将在其中查找这些定义。
  17. 右键单击 "JasperReports Definition" 节点,然后选择“新建”>“文件/文件夹”。
  18. 在“类别”面板中选择“其他”,在“文件类型”面板中选择“空文件”,然后单击“下一步”。
  19. 在“文件名”文本框中键入 TripReportByPerson.jrxml,然后按 Enter 键。将在 XML 编辑器中打开新文件。
  20. 复制以下 XML 标记并将其粘贴到空的 XML 文件中。

    代码样例 1:JasperReport 模板 TripReportByPerson.jrxml
    <?xml version="1.0"?>
    <!DOCTYPE jasperReport
      PUBLIC "-//JasperReports//DTD Report Design//EN"
      "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
    <jasperReport name="TripReportByPerson">
    
    <style name="Arial_Normal" isDefault="true" fontName="Arial" fontSize="12"
      isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"
      pdfFontName="Helvetica" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
    <style name="Arial_Bold" fontName="Arial" isDefault="false"  isBold="true"
      pdfFontName="Helvetica-Bold"/>
    <style name="Arial_Header1"  fontName="Arial" isDefault="false" fontSize="22"
      isBold="true" pdfFontName="Helvetica-Bold"/>
    
    <style name="Arial_Bold_White" fontName="Arial" forecolor="white"
      isDefault="false" fontSize="12" isBold="true" pdfFontName="Helvetica-Bold"/>
    
    <parameter name="LogoURL" class="java.net.URL"/>
    
    <field name="NAME" class="java.lang.String"/>
    <field name="TRIPID" class="java.lang.Integer"/>
    <field name="DEPDATE" class="java.util.Date"/>
    <field name="DEPCITY" class="java.lang.String"/>
    <field name="DESTCITY" class="java.lang.String"/>
    <field name="DESCRIPTION" class="java.lang.String"/>
    
    <group name="PersonGroup" minHeightToStartNewPage="84">
      <groupExpression>
      <![CDATA[$F{NAME}]]>
      </groupExpression>
      <groupHeader>
        <band height="64">
          <textField>
            <reportElement style="Arial_Bold" mode="Opaque" x="0" y="24"
              width="550" height="15" backcolor="#e0e0e0" />
            <textFieldExpression class="java.lang.String">
              <![CDATA["Scheduled Trips for " + $F{NAME}]]>
            </textFieldExpression>
          </textField>
        <line>
          <reportElement x="0" y="39" width="550" height="1" />
          <graphicElement />
        </line>
        <frame>
          <reportElement x="0" y="40" width="550" height="20"
            mode="Opaque" backcolor="lightGray"/>
          <staticText>
            <reportElement style="Arial_Bold_White" x="20" y="2" width="130" height="15"  />
            <text><![CDATA[Departure Date]]></text>
          </staticText>
          <staticText>
            <reportElement style="Arial_Bold_White" x="150" y="2" width="130" height="15"  />
            <text><![CDATA[Departure City]]></text>
          </staticText>
          <staticText>
            <reportElement style="Arial_Bold_White"  x="280" y="2" width="130" height="15" />
            <text><![CDATA[Destination City]]></text>
          </staticText>
          <staticText>
            <reportElement style="Arial_Bold_White" x="410" y="2" width="130" height="15" />
            <textElement textAlignment="Left" />
            <text><![CDATA[Purpose]]></text>
          </staticText>
          </frame>
        </band>
      </groupHeader>
    </group>
    
    <pageHeader>
      <band height="94">
        <image>
          <reportElement x="0" y="0" width="441" height="60"/>
          <graphicElement/>
          <imageExpression class="java.net.URL">
            <![CDATA[$P{LogoURL}]]>
          </imageExpression>
        </image>
        <line>
          <reportElement x="0" y="60" width="550" height="1"/>
          <graphicElement/>
        </line>
        <staticText>
          <reportElement style="Arial_Header1" x="0" y="60" width="445" height="30" />
          <text><![CDATA[Trip Report by Employee]]></text>
        </staticText>
      </band>
    </pageHeader>
    
    <detail>
      <band height="20">
        <textField pattern="dd/MM/yyyy">
          <reportElement x="20" y="0" width="100" height="20"/>
          <textFieldExpression class="java.util.Date">
            <![CDATA[$F{DEPDATE}]]>
          </textFieldExpression>
        </textField>
        <textField isBlankWhenNull="true">
          <reportElement x="150" y="0" width="100" height="20"/>
          <textFieldExpression class="java.lang.String">
            <![CDATA[$F{DEPCITY}]]>
          </textFieldExpression>
        </textField>
        <textField isBlankWhenNull="true">
          <reportElement x="280" y="0" width="100" height="20"/>
          <textFieldExpression class="java.lang.String">
            <![CDATA[$F{DESTCITY}]]>
          </textFieldExpression>
        </textField>
        <textField isBlankWhenNull="true">
          <reportElement x="410" y="0" width="100" height="20"/>
          <textFieldExpression class="java.lang.String">
            <![CDATA[$F{DESCRIPTION}]]>
          </textFieldExpression>
        </textField>
      </band>
    </detail>
    </jasperReport>
  21. 保存并关闭该文件。
  22. 在“文件”窗口中,展开 "TravelReport",然后双击 build.xml 以在编辑区域将其打开。
  23. 将以下脚本添加到 </project> 标记的前面。

    该脚本将覆盖 -post-compile 目标,IDE 会在编译 Java 源文件后调用此目标。目标脚本将编译位于 src/reports 文件夹中的任何 JRXML 文件,并将编译的报告放在 build/WEB-INF/reports 文件夹中。

    代码样例 2:build.xml 报告编译脚本
        <!-- Customize the following property to point to the folder
             in which you unpacked your Jasper Reports release -->
        <property name="jrc.home"
                  value="JasperReports-Install-Dir/jasperreports-1.3.0"/>
        <!-- Define the classpath used for report compilation -->
        <path id="jrc.classpath">
            <fileset dir="${jrc.home}/dist"
                         includes="*.jar"/>
            <fileset dir="${jrc.home}/lib"
                         includes="*.jar"/>
        </path>
        <!-- Define the custom Ant task that compiles report definitions -->
        <taskdef name="jrc"
                 classname="net.sf.jasperreports.ant.JRAntCompileTask">
            <classpath refid="jrc.classpath"/>
        </taskdef>
        <!-- Define the target that will compile reports, after Java compiles
             have been completed -->
        <target name="-post-compile"
                        description="Compile all Jasper Reports Definitions">
            <!-- Create the output directory first -->
            <mkdir dir="${build.web.dir}/WEB-INF/reports"/>
            <!-- Compile report definition -->
            <jrc srcdir="src/reports"
                      destdir="${build.web.dir}/WEB-INF/reports">
                <classpath
                    refid="jrc.classpath"/>
                <include
                    name="*.jrxml"/>
            </jrc>
            <!-- Omit the report definition sources from the webapp -->
            <delete>
                <fileset dir="${build.web.dir}/WEB-INF/classes"
                         includes="*.jrxml"/>
            </delete>
        </target>
    
  24. 修改 jrc.home 属性的值以指向解压缩 JasperReports zip 文件所在的文件夹。
  25. 保存并关闭该文件。
  26. 选择“生成”>“生成主项目”以调用 build.xml 脚本。
  27. 在“文件”窗口中,展开 "build" > "web" > "WEB-INF" > "reports",验证 IDE 是否生成了 TripReportByPerson.jasper 二进制文件。

    如果在“输出”窗口中看到生成错误,或者未创建二进制文件,请验证是否在 build.xml 文件中正确设置了 jrc.home 属性。

映射 JasperReports ImageServlet

JasperReports 框架包含一个名为 ImageServlet 的 Servlet,它用于在生成的 HTML 报告中显示图像。即使在您的报告中不包含图像,也必须添加此 Servlet 的映射,因为 JasperReports 会使用空图像作为间隔。

执行以下步骤可以将图像 URI 映射到 ImageServlet。当添加代码以便将报告导出为 HTML 页时,需要使用此图像 URI。
  1. 在“文件”窗口中,展开 "web" > "WEB-INF",然后双击 web.xml 节点以在 XML 编辑器中将其打开。

    请确保编辑的是 "web" > "WEB-INF" 下的 web.xml 文件,而不是 "build" > "web" > "WEB-INF" 下的文件。如果编辑了 "build" > "web" > "WEB-INF" 下的 web.xml 文件,则在下次生成项目时会丢失所做的更改。
  2. 在编辑工具栏中,单击 "Servlet" 以打开 Servlet 编辑器。
  3. 在 Servlet 编辑器中,单击“添加 Servlet 元素”。

    将出现“添加 Servlet”对话框,如下图所示。

    图 6:“添加 Servlet”对话框 图 6:“添加 Servlet”对话框
  4. 在“添加 Servlet”对话框中键入以下值,然后单击“确定”。

    文本框
    Servlet 名称 ImageServlet
    Servlet 类 net.sf.jasperreports.j2ee.servlets.ImageServlet
    URL 模式 /image
  5. 关闭 web.xml 并保存所做的更改。

    现在,当应用程序收到要求定位到 image 的请求时,就应该将请求发送至 ImageServlet 实例。

添加报告生成逻辑

执行以下步骤后,可以将逻辑添加到应用程序 Bean 中以生成报告。
  1. 在“项目”窗口中,双击“应用程序 Bean”节点以便在编辑区域中打开 ApplicationBean1.java。
  2. 在文件结尾处的最后一个花括号前面添加以下代码。

    代码样例 3:报告生成代码
    /**
     * <p>Prefix to the resource name for compiled reports.</p>
     */
    private static final String PREFIX = "/WEB-INF/reports/";
    
    
    /**
     * <p>Suffix to the resource name for compiled reports.</p>
     */
    private static final String SUFFIX = ".jasper";
    
    
    /**
     * <p>Valid content types for reports that we can produce.</p>
     */
    private static final String[] VALID_TYPES =
    { "text/html",            // Standard HTML representation
      "application/pdf",      // Adobe Portable Document Format
    };
    
    
    /**
     * <p>Generate the specified report, in the specified output
     * format, based on the specified data.</p>
     *
     * @param name Report name to be rendered
     * @param type Content type of the requested report ("application/pdf"
     *  or "text/html")
     * @param data <code>ResultSet</code> containing
     *  the data to report
     *
     * @exception IllegalArgumentException if the specified
     *  content type is not recognized
     * @exception IllegalArgumentException if no compiled report definition
     * for the specified name can be found
     */
    public void jasperReport(String name, String type,
                             ResultSet data) {
        jasperReport(name, type, data, new HashMap());
    }
    
    /**
     * <p>Generate the specified report, in the specified output
     * format, based on the specified data.</p>
     *
     * @param name Report name to be rendered
     * @param type Content type of the requested report ("application/pdf"
     *  or "text/html")
     * @param data <code>ResultSet</code> containing the data to report
     * @param params <code>Map</code> of additional
     *   report parameters
     *
     * @exception IllegalArgumentException if the specified
     *  content type is not recognized
     * @exception IllegalArgumentException if no compiled report definition
     * for the specified name can be found
     */
    public void jasperReport(String name, String type,
            ResultSet data, Map params) {
    
        // Validate that we recognize the report type
        // before potentially wasting time filling the
        // report with data
        boolean found = false;
        for (int i = 0; i < VALID_TYPES.length; i++) {
            if (VALID_TYPES[i].equals(type)) {
                found = true;
                break;
            }
        }
        if (!found) {
            throw new IllegalArgumentException("Invalid report type '"
                    + type
                    + "' requested");
        }
    
        // Look up the compiled report design resource
        ExternalContext econtext = getExternalContext();
        InputStream stream = econtext.getResourceAsStream(PREFIX + name
                    + SUFFIX);
        if (stream == null) {
            throw new IllegalArgumentException("Unknown report name '"
                    + name
                    + "' requested");
        }
    
        try {
            data.beforeFirst();
        } catch (Exception e) {
            throw new FacesException(e);
        }
    
        // Fill the requested report with the specified data
        JRResultSetDataSource ds = new JRResultSetDataSource(data);
        JasperPrint jasperPrint = null;
        try {
            jasperPrint = JasperFillManager.fillReport(
                stream, params, ds);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                ;
            }
        }
    
        // Configure the exporter to be used, along with the custom
        // parameters specific to the exporter type
        JRExporter exporter = null;
        HttpServletResponse response = (HttpServletResponse)
        econtext.getResponse();
        FacesContext fcontext = FacesContext.getCurrentInstance();
        try {
            response.setContentType(type);
            if ("application/pdf".equals(type)) {
              exporter = new JRPdfExporter();
              exporter.setParameter(JRExporterParameter.JASPER_PRINT,
                jasperPrint);
              exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                response.getOutputStream());
            } else if ("text/html".equals(type)) {
              exporter = new JRHtmlExporter();
              exporter.setParameter(JRExporterParameter.JASPER_PRINT,
                jasperPrint);
              exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,
                response.getWriter());
              // Make images available for the HTML output
              HttpServletRequest request =
                (HttpServletRequest)
                fcontext.getExternalContext().getRequest();
              request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);
              exporter.setParameter(
                JRHtmlExporterParameter.IMAGES_MAP, new HashMap());
              // The following statement requires mapping /image
              // to the imageServlet in the web.xml.
              //
              // This servlet serves up images including the px
              // images for spacing.
              //
              // Serve up the images directly so we
              // don't incur the extra overhead associated with
              // with a JSF request for a non-JSF entity.
              exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
                request.getContextPath() + "/image?image=");
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        }
    
        // Enough with the preliminaries ...
        // export the report already
        try {
            exporter.exportReport();
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        }
    
        // Tell JavaServer Faces that no output is required
        fcontext.responseComplete();
    
    }
  3. 在源代码中单击鼠标右键,然后从弹出式菜单中选择“修复导入”。在“修复导入”对话框中,验证 java.io.InputStream 是否出现在 InputStream 类的“全限定名称”字段中,以及 java.sql.ResultSet 是否出现在 ResultSet 类的“全限定名称”字段中。
  4. 单击“确定”。
  5. 保存并关闭该文件。

创建数据库查询

在此应用程序中,您使用了相同的数据库查询结果集在 Web 页和生成的报告中显示行程信息。您可以使用查询编辑器来设计数据库查询,如下图所示。

图 7:行程结果集的查询编辑器设置
图 7:行程结果集的查询编辑器设置
  1. 在编辑区域,单击 "Page1" 标签以在可视设计器中查看该页面。
  2. 在“运行环境”窗口中,依次展开“数据库”、TRAVEL 数据库的 jdbc 节点和“表”。
  3. 将 "TRIP" 节点拖放到页面上的空白位置。
  4. 在“概要”窗口中,展开 "SessionBean1",然后双击 "tripRowSet" 以打开查询编辑器。
  5. 在顶部面板的 TRIP 表中,清除 PERSONID、TRIPTYPEID 和 LASTUPDATED 的复选框标记。
  6. 将 PERSON 节点从“运行环境”窗口拖放到顶部面板的 TRIP 表旁边。
  7. 在 PERSON 表中,清除 PERSONID、JOBTITLE、FREQUENTFLYER 和 LASTUPDATED 的复选框标记。
  8. 将 TRIPTYPE 节点从“运行环境”窗口拖放到顶部面板的 PERSON 表旁边。
  9. 在 TRIPTYPE 表中,清除 TRIPTYPEID、NAME 和 LASTUPDATED 的复选框标记。
  10. 在网格面板的 TRAVEL.PERSON 表的 NAME 行中,从“排序类型”列的下拉列表中选择“升序”。

    IDE 会将排序顺序设置为 1。
  11. 在网格面板 TRAVEL.TRIP 表的 DEPDATE 行中,从“排序类型”列的下拉列表中选择“升序”。

    IDE 会将排序顺序设置为 2。
  12. 关闭 tripRowSet 的查询编辑器。

创建行程报告页

在本部分,您将为 Page1 添加一个表以显示行程数据,并添加一些按钮以生成 HTML 和 PDF 格式的报告,如下图所示。

图 8:Page1
图 8:Page1
  1. 在可视设计器中显示 Page1。
  2. 将一个表组件从组件面板拖放到页面上。
  3. 右键单击表组件,然后从弹出式菜单中选择“表布局”。
  4. 在“表布局”对话框中,从“获取数据来自”下拉列表中选择 "tripDataProvider"。
  5. 在“选定”列表中选择 "PERSON.NAME",然后重复单击“上移”按钮,直至将 PERSON.NAME 移至列表的顶部。
  6. 单击“选项”标签。
  7. 在“标题”文本框中键入 Trips
  8. 选择“启用分页”。
  9. 单击“确定”关闭该对话框。
  10. 将一个按钮组件拖放到表组件的上方,键入 View Report,然后按 Enter 键。
  11. 在“属性”窗口中,将 id 属性设置为 viewReportBtn
  12. 单击位于 action 属性旁边的省略号 (...) 按钮,从下拉列表中选择 "viewReportBtn_action",然后单击“确定”。
  13. 将一个按钮组件拖放到 "View Report" 按钮的旁边,键入 Create PDF,然后按 Enter 键。
  14. 在“属性”窗口中,将 id 属性设置为 createPdfBtn
  15. 单击位于 action 属性旁边的省略号 (...) 按钮,从下拉列表中选择 "createPdfBtn_action",然后单击“确定”。
  16. 双击 "View Report" 按钮以显示 viewReportBtn_action 方法的 Java 源代码。
  17. 将下面以粗体显示的代码添加到 viewReportBtn_action 方法的主体中。

    代码样例 4:viewReportBtn_action 方法
        public String viewReportBtn_action() {
            // Free up the rowset resources
            tripDataProvider.close();
            Map fillParams = new HashMap();
            // The above statement generates warnings with Java SE 1.5
            // To eliminate the warnings, replace with the
            // following statement:
            // Map<String, URL> fillParams =
            //   new HashMap<String, URL.>>();
            try {
                fillParams.put
                  ("LogoURL",
                   getExternalContext().getResource("/resources/images/logo.gif"));
                getApplicationBean1().jasperReport
                  ("TripReportByPerson", "text/html",
                   getSessionBean1().getTripRowSet(), fillParams);
            } catch (Exception e) {
                log("Exception generating report", e);
                error("Exception generating report: " + e);
            }
            return null;
        }
    
  18. 滚动至 createPdfBtn_action 方法并添加下面以粗体显示的代码。

    代码样例 5:createPdfBtn_action 方法
        public String createPdfButton_action() {
            // Free up the rowset resources
            tripDataProvider.close();
            Map fillParams = new HashMap();
            try {
                fillParams.put
                  ("LogoURL",
                   getExternalContext().getResource("/resources/images/logo.gif"));
                getApplicationBean1().jasperReport
                  ("TripReportByPerson", "application/pdf",
                   getSessionBean1().getTripRowSet(), fillParams);
            } catch (Exception e) {
                log("Exception generating report", e);
                error("Exception generating report: " + e);
            }
            return null;
        }
    
  19. 在源代码中单击鼠标右键,然后从弹出式菜单中选择“修复导入”。
  20. 在主工具栏中,单击“运行主项目”以生成、部署并运行此 Web 应用程序。
  21. 在 Web 应用程序中,单击 "View Report" 以查看 HTML 格式的报告。

    如果看到中断的图像,请打开 "web" > "WEB-INF" > "web.xml",并确保 ImageServlet 条目存在。有时,IDE 可能不保存新添加的条目。
  22. 单击“后退”按钮,然后单击 "Create PDF" 以查看 PDF 格式的报告。

小结

下面列出了在 NetBeans Visual Web Pack 项目中使用 JasperReports 框架的主要步骤:
  1. 通过 http://www.jasperforge.org Web 站点下载 JasperReports 框架,并对其进行解压缩。
  2. 使用库管理器创建一个 JasperReports 库。这可以方便地为 Web 应用程序添加所需的 JasperReports JAR 文件。
  3. 要为 Web 应用程序添加 JasperReports 库,请在“项目”窗口中右键单击“库”节点,然后选择“添加库”。
  4. 在“选项”对话框中,使用 XML 对象的“扩展名和 MIME 类型”属性将 jrxml 添加到 XML 对象列表中。通过执行此操作,IDE 将在 XML 编辑器中打开 jrxml 文件。
  5. web.xml 文件中,为 net.sf.jasperreports.j2ee.servlets.ImageServlet 添加映射。
  6. 将逻辑添加到应用程序 Bean 中以生成报告。
  7. 在创建报告后,调用 facesContext.responseComplete( ) 以终止当前的请求生命周期。
  8. 如果生成的是 HTML 报告,请使用 IMAGES_URI 参数传递 ImageServlet 类所对应的 URI。例如,如果将 URI 设置为 /image,请将 IMAGES_URI 参数设置为 request.getContextPath() + "/image?image="
  9. 可以将一个缓存行集(例如,将数据提供器添加到页面时 IDE 创建的缓存行集)作为数据源来填充报告。请确保在填充报告之前调用数据提供器的 close 方法。

另请参见


此页的最新修改时间:2007 年 5 月 24 日


Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by