目录

JasperReports - Scriptlets( Scriptlets)

我们在前面的章节中已经看到,报告中显示的数据通常是从报告参数和报告字段中提取的。 可以使用报告变量及其表达式处理此数据。 有些情况下,使用报表表达式或变量无法轻松实现复杂功能。 这样的示例可能是复杂的字符串操作,构建映射,或内存中的对象列表或使用第三方Java API操作日期。 对于这种情况,JasperReports为我们提供了一个使用Scriptlets执行此操作的简单而强大的方法。

Scriptlet是每次报告事件发生时执行的Java代码序列。 报告变量的值可以通过scriptlet受到影响。

Scriptlet宣言

我们可以用两种方式声明一个scriptlet -

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

  • 在报告模板(JRXML)中使用元素“ jasperReport ”的属性scriptletClass 。 通过使用scriptlet的完全限定名称(包括整个包名称)设置此属性,我们指示我们要使用scriptlet。 使用此属性创建的scriptlet实例的行为类似于scriptlet列表中的第一个scriptlet,并具有预定义的名称REPORT。

Scriptlet类

scriptlet是一个java类,必须扩展以下任一类 -

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

  • net.sf.jasperreports.engine.JRDefaultScriptlet - 此类包含JRAbstractScriptlet中每个方法的默认空实现。 开发人员只需要为他/她的项目实现他/她所需的方法。

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

S.NO 方法和描述
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()

在评估报告的详细信息部分中的每个记录之前调用。

10

public void afterDetailEval()

在评估报告的详细信息部分中的每个记录之后调用。

每个报告可以指定任意数量的scriptlet。 如果没有为报告指定scriptlet,则引擎仍会创建单个JRDefaultScriptlet实例,并使用内置的REPORT_SCRIPTLET参数进行注册。

我们可以向scriptlet添加我们需要的任何其他方法。 报表可以使用内置参数REPORT_SCRIPTLET调用这些方法。

全局Scriptlets

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

报告总督

调控器只是全局scriptlet的扩展,使我们能够解决报表引擎在运行时进入无限循环的问题,同时生成报表。 在设计时无法检测到无效的报告模板,因为大多数情况下,进入无限循环的条件取决于在运行时送入引擎的实际数据。 报告总督帮助决定某个报告是否已进入无限循环,他们可以阻止它。 这可以防止运行报表的计算机的资源耗尽。

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

  • net.sf.jasperreports.governors.MaxPagesGovernor - 这是一个全局scriptlet,它正在寻找两个配置属性来决定它是否适用于当前正在运行的报表。 配置属性是 -

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

    • net.sf.jasperreports.governor.max.pages=[integer]

  • net.sf.jasperreports.governors.TimeoutGovernor - 这也是一个全局scriptlet,它正在寻找以下两个配置属性来决定它是否适用。

    配置属性是 -

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

    • net.sf.jasperreports.governor.timeout=[milliseconds]

两个调控器的属性可以在jasperreports.properties文件中全局设置,也可以在报表级别设置为自定义报表属性。 这很有用,因为不同的报告可能有不同的估计大小或超时限制,也可能因为您可能需要打开所有报告的调控器,同时为某些报告关闭,反之亦然。

例子 (Example)

我们来编写一个scriptlet类( MyScriptlet )。 文件C:\tools\jasperreports-5.0.1\test\src\com\iowiki\MyScriptlet.java的内容如下 -

package com.iowiki;
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.";
   }
}

上述scriptlet类的详细信息如下 -

  • afterReportInit方法中,我们将值设置为变量"someVar" this.setVariableValue(“someVar”,new String(“此变量值由scriptlet修改。”))。

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

接下来,我们将在现有报告模板(章节Report Designs )中添加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.iowiki.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类。

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

  • 上面的报告模板在Summary字段中有一个方法调用,它说明了如何编写新方法(在scriptlet中)并在报告模板中使用它们。 ( $P{REPORT_SCRIPTLET}.hello()

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

package com.iowiki;
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\iowiki\DataBean.java的内容如下所示 -

package com.iowiki;
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\iowiki\DataBeanList.java的内容如下所示 -

package com.iowiki;
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;
   }
}

报表生成 (Report Generation)

我们将使用常规的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.iowiki.JasperReportFill (viewFullReport是默认目标)为 -

C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.iowiki.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 http://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.iowiki.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示例

在这里,我们看到MyScriptlet类显示两条消息 -

  • 在标题部分 - This variable value was modified by the scriptlet
  • 在底部 - Hello! I'm the report's scriptlet object. Hello! I'm the report's scriptlet object.
↑回到顶部↑
WIKI教程 @2018