报表脚本程序(Scriptlets)



在我们之前的章节中,我们已经看到,报表上显示的数据通常是从报表参数和报表字段中获取的。可以使用报表变量及其表达式来处理这些数据。在某些情况下,使用报表表达式或变量难以轻松实现复杂的功能。例如,复杂的字符串操作、内存中对象映射或列表的构建,或者使用第三方 Java API 操作日期。对于这种情况,JasperReports 提供了一种简单而强大的方法,可以使用脚本程序 (Scriptlets) 来实现。

脚本程序是每次发生报表事件时都会执行的 Java 代码序列。可以通过脚本程序影响报表变量的值。

脚本程序声明

我们可以通过两种方式声明脚本程序:

  • 使用<scriptlet> 元素。此元素具有name 属性和class 属性。class 属性应指定类的名称,该类扩展了JRAbstractScriptlet 类。该类必须在报表填充时在类路径中可用,并且必须具有一个空构造函数,以便引擎可以动态实例化它。

  • 使用报表模板 (JRXML) 中<jasperReport> 元素的scriptletClass 属性。通过将此属性设置为脚本程序的完全限定名称(包括整个包名),我们指示我们要使用一个脚本程序。使用此属性创建的脚本程序实例充当脚本程序列表中的第一个脚本程序,并具有预定义的名称 REPORT。

脚本程序类

脚本程序是一个 Java 类,它必须扩展以下类之一:

  • net.sf.jasperreports.engine.JRAbstractScriptlet - 此类包含许多必须在每个实现中被覆盖的抽象方法。这些方法会在适当的时候由 JasperReports 自动调用。开发者必须实现所有抽象方法。

  • net.sf.jasperreports.engine.JRDefaultScriptlet - 此类包含 JRAbstractScriptlet 中每个方法的默认空实现。开发者只需要实现项目所需的那些方法。

下表列出了上述类中的方法。在报表填充阶段,这些方法会在适当的时间由报表引擎调用。

序号 方法和描述
1

public void beforeReportInit()

报表初始化之前调用。

2

public void afterReportInit()

报表初始化之后调用。

3

public void beforePageInit()

初始化每一页之前调用。

4

public void afterPageInit()

初始化每一页之后调用。

5

public void beforeColumnInit()

初始化每一列之前调用。

6

public void afterColumnInit()

初始化每一列之后调用。

7

public void beforeGroupInit(String groupName)

初始化参数中指定的组之前调用。

8

public void afterGroupInit(String groupName)

初始化参数中指定的组之后调用。

9

public void beforeDetailEval()

评估报表 detail 部分中的每个记录之前调用。

10

public void afterDetailEval()

评估报表 detail 部分中的每个记录之后调用。

每个报表可以指定任意数量的脚本程序。如果未为报表指定脚本程序,引擎仍然会创建一个 JRDefaultScriptlet 实例并将其注册到内置的 REPORT_SCRIPTLET 参数。

我们可以向脚本程序添加任何其他所需的方法。报表可以通过使用内置参数 REPORT_SCRIPTLET 来调用这些方法。

全局脚本程序

我们可以通过另一种方式将脚本程序与报表关联,即全局声明脚本程序。这使得脚本程序适用于在给定的 JasperReports 部署中填充的所有报表。脚本程序可以作为扩展添加到 JasperReports 中,这使得这一操作非常容易。脚本程序扩展点由net.sf.jasperreports.engine.scriptlets.ScriptletFactory 接口表示。JasperReports 将在运行时加载通过扩展程序提供的所有脚本程序工厂。然后,它将向每个工厂询问它们想要应用于当前正在运行的报表的脚本程序实例列表。在请求脚本程序实例列表时,引擎会提供一些上下文信息,工厂可以使用这些信息来决定哪些脚本程序实际上适用于当前报表。

报表管理器 (Report Governors)

管理器只是全局脚本程序的扩展,使我们能够解决报表引擎在运行时生成报表时进入无限循环的问题。无效的报表模板在设计时无法检测到,因为大多数情况下,进入无限循环的条件取决于在运行时馈送到引擎的实际数据。报表管理器有助于确定某个报表是否已进入无限循环,并可以停止它。这可以防止运行报表的机器资源耗尽。

JasperReports 具有两个简单的报表管理器,可以根据指定的最大页数或指定的超时时间间隔停止报表执行。它们是:

  • net.sf.jasperreports.governors.MaxPagesGovernor - 这是一个全局脚本程序,它查找两个配置属性以决定它是否应用于当前正在运行的报表。配置属性为:

    • net.sf.jasperreports.governor.max.pages.enabled=[true|false]

    • net.sf.jasperreports.governor.max.pages=[整数]

  • net.sf.jasperreports.governors.TimeoutGovernor - 这也是一个全局脚本程序,它查找以下两个配置属性以决定它是否应用。

    配置属性为:

    • net.sf.jasperreports.governor.timeout.enabled=[true|false]

    • net.sf.jasperreports.governor.timeout=[毫秒]

这两个管理器的属性可以在 jasperreports.properties 文件中全局设置,也可以在报表级别作为自定义报表属性设置。这很有用,因为不同的报表可以具有不同的估计大小或超时限制,而且您可能希望为所有报表启用管理器,而为某些报表关闭管理器,反之亦然。

示例

让我们编写一个脚本程序类 (MyScriptlet)。文件 C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\MyScriptlet.java 的内容如下:

package com.tutorialspoint;

import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRScriptletException;


public class MyScriptlet extends JRDefaultScriptlet {

   public void afterReportInit() throws JRScriptletException{
      System.out.println("call afterReportInit()");
      // this.setVariableValue("AllCountries", sbuffer.toString());
      this.setVariableValue("someVar", new String("This variable value 
         was modified by the scriptlet."));
   }

   public String hello() throws JRScriptletException {
      return "Hello! I'm the report's scriptlet object.";
   }

}

上述脚本程序类的详细信息如下:

  • afterReportInit 方法中,我们将一个值设置为变量"someVar" this.setVariableValue("someVar", new String("This variable value was modified by the scriptlet."));

  • 在类的末尾,定义了一个名为'hello' 的额外方法。这是一个示例方法,可以添加到实际返回值而不是设置变量的 Scriptlet 中。

接下来,我们将脚本程序类引用添加到我们现有的报表模板中(章节 报表设计)。修改后的报表模板 (jasper_report_template.jrxml) 如下所示。将其保存到 C:\tools\jasperreports-5.0.1\test 目录:

<?xml version = "1.0"?>
<!DOCTYPE jasperReport PUBLIC
   "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<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_report_template" pageWidth = "595"
   pageHeight = "842" columnWidth = "515"
   leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50"
   scriptletClass = "com.tutorialspoint.MyScriptlet">
	
   <style name = "alternateStyle" fontName = "Arial" forecolor = "red">
      
      <conditionalStyle>
         <conditionExpression>
            <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]>
         </conditionExpression>
			
         <style forecolor = "blue" isBold = "true"/>
      </conditionalStyle>
   </style>
   
   <parameter name = "ReportTitle" class = "java.lang.String"/>
   <parameter name = "Author" class = "java.lang.String"/>

   <queryString>
      <![CDATA[]]>
   </queryString>

   <field name = "country" class = "java.lang.String">
      <fieldDescription>
         <![CDATA[country]]>
      </fieldDescription>
   </field>

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

   <variable name = "countNumber" class = "java.lang.Integer" 
      calculation = "Count">
      <variableExpression><
         ![CDATA[Boolean.TRUE]]>
      </variableExpression>
   </variable>

   <variable name = "someVar" class = "java.lang.String">
      <initialValueExpression>
        <![CDATA["This is the initial variable value."]]>
      </initialValueExpression>
   </variable>

   <title>
      <band height = "100">
         
         <line>
            <reportElement x = "0" y = "0" width = "515" height = "1"/>
         </line>
         
         <textField isBlankWhenNull = "true" bookmarkLevel = "1">
            <reportElement x = "0" y = "10" width = "515" height = "30"/>
            
            <textElement textAlignment = "Center">
              <font size = "22"/>
            </textElement>
            
            <textFieldExpression class = "java.lang.String">
              <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>
				
            <anchorNameExpression>
               <![CDATA["Title"]]>
            </anchorNameExpression>
         </textField>
        
         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "40" width = "515" height = "20"/>
            
            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>
            
            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{Author}]]>
            </textFieldExpression>
         </textField>
         
         <textField isBlankWhenNull = "true">
            <reportElement  x = "0" y = "50" width = "515" 
               height = "30" forecolor = "#993300"/>
             
            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>
            
            <textFieldExpression class = "java.lang.String">
               <![CDATA[$V{someVar}]]>
            </textFieldExpression>
				
         </textField>

      </band>
   </title>

   <columnHeader>
      <band height = "23">
         
         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" 
               width = "535" height = "15"
               backcolor = "#70A9A9" />
            
            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>
				
            <textElement />
				
            <text>
               <![CDATA[]]>
            </text>
				
         </staticText>
         
         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />
                
            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>
            
            <text><![CDATA[Country]]></text>
         </staticText>
         
         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />
            
            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>
				
            <text><![CDATA[Name]]></text>
         </staticText>
      
      </band>
   </columnHeader>

   <detail>
      <band height = "16">
         
         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" 
               width = "535"	height = "14"
               backcolor = "#E5ECF9" />
            
            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>
				
            <textElement />
				
            <text>
               <![CDATA[]]>
            </text>
         </staticText>
         
         <textField>
            <reportElement style = "alternateStyle" x="414" y = "0" 
               width = "121" height = "15" />
            
            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>
            
				
            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>
         
         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />
            
            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>
      
      </band>
   </detail>
   
   <summary>
      <band height = "45">
            
         <textField isStretchWithOverflow = "true">
            <reportElement x = "0" y = "10" width = "515" height = "15" />
            <textElement textAlignment = "Center"/>
               
            <textFieldExpression class = "java.lang.String">
               <![CDATA["There are " + String.valueOf($V{REPORT_COUNT}) +
                  " records on this report."]]>
            </textFieldExpression>
         </textField>
         
         <textField isStretchWithOverflow = "true">
            <reportElement positionType = "Float" x = "0" y = "30" width = "515"
               height = "15" forecolor = "# 993300" />
               
            <textElement textAlignment = "Center">
               <font size = "10"/>
            </textElement>
               
            <textFieldExpression class = "java.lang.String">
               <![CDATA[$P{REPORT_SCRIPTLET}.hello()]]>
            </textFieldExpression>
            
         </textField>
         
      </band>
   </summary>
	
</jasperReport>

修改后的报表模板的详细信息如下:

  • 我们在<jasperReport> 元素的scriptletClass 属性中引用了 MyScriptlet 类。

  • 脚本程序只能访问而不能修改报表字段和参数。但是,脚本程序可以修改报表变量的值。这可以通过调用 setVariableValue() 方法来实现。此方法定义在 JRAbstractScriptlet 类中,该类始终是任何脚本程序的父类。在这里,我们定义了一个变量someVar,它将被 MyScriptlet 修改为具有值This value was modified by the scriptlet

  • 上述报表模板在 Summary band 中有一个方法调用,说明如何编写新方法(在脚本程序中)并在报表模板中使用它们。($P{REPORT_SCRIPTLET}.hello())

报表填充的 Java 代码保持不变。文件C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java 的内容如下:

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName = 
         "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource = new 
         JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

POJO 文件C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java 的内容如下:

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

文件C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java 的内容如下:

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);
      
      return dataBean;
   }
}

报表生成

我们将使用常规的 ANT 构建过程来编译和执行上述文件。文件 build.xml(保存在目录 C:\tools\jasperreports-5.0.1\test 下)的内容如下所示。

导入文件 - baseBuild.xml 来自章节 环境设置,应与 build.xml 放在同一目录下。

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
   <import file = "baseBuild.xml" />
   
   <target name = "viewFillReport" depends = "compile,compilereportdesing,run"
      description = "Launches the report viewer to preview 
      the report stored in the .JRprint file.">
      
      <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
         <arg value = "-F${file.name}.JRprint" />
         <classpath refid = "classpath" />
      </java>
   </target>
   
   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">
      
      <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>
      
      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>
   
   </target>

</project>

接下来,让我们打开命令行窗口并转到放置 build.xml 的目录。最后,执行命令ant -Dmain-class=com.tutorialspoint.JasperReportFill(viewFullReport 是默认目标)如下:

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml

clean-sample:
   [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
   [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
   [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting to bu
   [javac] Compiling 4 source files to C:\tools\jasperreports-5.0.1\test\classes

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See https://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.
   [java] call afterReportInit()
   [java] call afterReportInit()

viewFillReport:
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

BUILD SUCCESSFUL
Total time: 18 minutes 49 seconds

上述编译的结果是,将打开一个 JasperViewer 窗口,如下面的屏幕所示:

Jasper Report Scriplet Example

在这里,我们看到显示了来自 MyScriptlet 类的两条消息:

  • 在标题部分 - This variable value was modified by the scriptlet
  • 在底部 - Hello! I'm the report's scriptlet object.
广告
© . All rights reserved.