我们在前面的章节中已经看到,报告中显示的数据通常是从报告参数和报告字段中提取的.可以使用报告变量及其表达式处理此数据.有些情况下,使用报表表达式或变量无法轻松实现复杂功能.这样的示例可能是复杂的字符串操作,构建映射,或内存中的对象列表或使用第三方Java API操作日期.对于这种情况,JasperReports通过 Scriptlets 为我们提供了一种简单而强大的方法.
Scriptlet是每次报告时执行的Java代码序列事件发生.报告变量的值可以通过scriptlet受到影响.
我们可以用两种方式声明一个scriptlet :
使用< scriptlet >元件.此元素具有 name 属性和 class 属性. 类属性应指定类的名称,该类扩展 JRAbstractScriptlet 类.该类必须在报告填充时在类路径中可用,并且必须具有空构造函数,以便引擎可以动态实例化它.
使用属性 scriptletClass 元素< jasperReport >,在报告模板(JRXML)中.通过使用scriptlet的完全限定名称(包括整个包名称)设置此属性,我们指示我们要使用scriptlet.使用此属性创建的scriptlet实例的行为类似于scriptlet列表中的第一个scriptlet,并具有
预定义名称REPORT.
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参数进行注册.
我们可以添加我们需要的任何其他方法小脚本.报告可以使用内置参数REPORT_SCRIPTLET来调用这些方法.
我们可以将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 = [毫秒]
两个调控器的属性可以在jasperreports.properties文件中全局设置,也可以在报表级别设置为自定义报表属性.这很有用,因为不同的报告可能有不同的估计大小或超时限制,也因为您可能需要为所有报告启用调控器,而为某些报告启用它,反之亦然.
让我们编写一个scriptlet类( MyScriptlet ).文件C:\tools \jasperreports-5.0.1 \test\src\com\it1352\MyScriptlet.java的内容如下 :
package com.it1352; 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". setVariableValue("someVar",new String("此变量值由scriptlet修改.")).
在课程结束时,额外已经定义了名为'hello'的方法.这是一个可以添加到实际返回值的Scriptlet的方法示例,而不是设置变量.
下一步,我们将在现有的报告模板中添加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.IT屋.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类.元件.
Scriptlets只能访问,但不能修改报告字段和参数.但是,scriptlet可以修改报表变量值.这可以通过调用setVariableValue()方法来完成.此方法在JRAbstractScriptlet类中定义,该类始终是任何scriptlet的父类.在这里,我们定义了一个变量 someVar ,它将被MyScriptlet修改为具有值该值由scriptlet修改.
上述报告模板在摘要带中有一个方法调用,说明如何编写新方法(在scriptlet中)并在报告模板中使用它们. ( $ P {REPORT_SCRIPTLET} .hello())
报告填充的java代码保持不变.文件 C:\tools\jasperreports-5.0.1\test\src\com\it1352\ JapersReportFill.java 的内容如下所示 :
package com.it1352; 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\it1352\ DataBean.java 如下所示 :
package com.it1352; 公共类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\it1352\ DataBeanList.java 如下所示 :
package com. it1352; 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; } }
我们将编译并执行上述文件我们定期的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.it1352.JasperReportFill (viewFullReport是默认目标)为 :
<?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
由于上面的编译,JasperViewer窗口打开up如下面给出的屏幕所示 :
这里我们看到两条消息显示在MyScriptlet类和减号中;
在标题部分 : 此变量值由scriptlet修改
在底部和底部; 您好!我是报告的scriptlet对象.