JasperReport 和struts2的整合

    技术2022-06-22  55

    JasperReport是一个报表制作程序。用户需要按照它制定的规则编写一个xml文件,然后得到用户需要输出的格式文件。而iReport是一个制作JasperReport的xml文件的可视化开发 工具,该库完全利用Java编写。可以用于在各种Java应用程序中,包括J2EE、WEB应用程序中生成动态内容。 1.iReort。

    Report Life Cycle Before we start working with iReport, let's learn about the life cycle of a report. When you design a report using iReport you are creating a JRXML file, which is an XML document that contains the definition of the report layout. The layout is completely designed in a visual way, so you can ignore the real structure of the JRXML file. Before executing a report, the JRXML must be compiled in a binary object called a Jasper file. This compilation is done for performance reasons. Jasper files are what you need to ship with your application in order to run the reports. The report execution is performed by passing a Jasper file and a data source to JasperReports. There are plenty of types of data sources, it's possible to fill a Jasper file from an SQL query, an XML file, a csv file, an HQL(Hibernate Query Language) query, a collection of JavaBeans, etc... If you don't find a suitable data source, JasperReports is very flexible and allows you to write your own custom data source. With a Jasper file and a data source, JasperReports is able to generate the final document in the format you prefer. iReport also lets you configure data sources and use them to test your reports. In many cases, data-driven wizards can help you design your reports much quicker. iReport includes the JasperReports engine itself to let you preview your report output, test, and refine your reports.

    To create the new connection in iReport, open the datasources/connections dialog by clicking its icon in the tool bar, as shown in Figure 2.

    Figure 2

    Click New, choose Database JDBC connection as shown in Figure 3, and use the following settings for the sample HSQL database, as shown in Figure 4 below:

    Name: JasperReports Sample

    JDBCDriver: org.hsqldb.jdbcDriver

    Url: jdbc:hsqldb:hsql://localhost

    Username: sa

    Password: [none]

    Figure 3

    Figure 4

    As said above, you can use your favorite database, in that case you have to provide the right URL, the JDBC driver and credentials. iReport proposes a list of well known database drivers. If the one you need is not present, just type the name. If it is present and it is highlighted in red it means that the driver is not available in the classpath and must be added. To do so, select Tools > Options > iReport > Classpath and add the required JARs to the classpath. Also, it's good practice to test the connection before saving it. When done, the new connection appears in the connections list and is automatically selected as the default, active connection:

    Figure 5

    Now, let's create the new report. Select File > New .

    Figure 6

    In the template chooser that appears, select a blank report and click Open this Template . Select a name and location to story the new file, click next and then finish. Your blank report now appears in the designer:

     

    Click the button representing a database query in the designer tool bar:

    Figure 8

    This opens the Query dialog to define the query that retrieves data to fill the report. The SQL query is stored inside the report and can accept parameters to filter the data using the syntax $P{} (for standard parameters) and $P!{} (to use a parameter as SQL chunk). Again we want to keep things simple in this tutorial, so we will not use any parameters. Type the following query to select all the fields/columns in the orders table:

    select * from orders

    Figure 9

    Of course, you can use any table for this example. The orders table is available in the sample database we are using. If you don't know SQL, you can use the visual SQL query builder by clicking the Query designer button. As you type the query, iReport executes it to extract all the fields (columns) available in the query. The fields are listed on the bottom portion of the window. If there is an error in the SQL, you'll get a message that explains what's wrong. When the query is valid, click OK . iReport lists all the discovered fields in the report inspectory, so they can be used in the report and displayed using text fields and other elements.

    To print the value of a field in the report, drag a field object from the report inspector to the design view. For example, drag a field into the detail band, a section of the report that is printed for each record/row in the query results. The title and the summary bands are printed just once in each report, while the page header and footer are printed once at the top and bottom of each page, respectively.

    Figure 10

    When the field object is dragged inside the detail band, iReport creates a textfield element and sets the textfield expression for that element to $F{SHIPNAME}. This is a simple expression to print the value of the field SHIPNAME (the syntax $F{}). Repeat the same operation for other fields and format the textfields element by stretching, dragging and aligning them. It is important that the textfields are all placed within the detail band.

    To preview the report, switch to the preview mode by clicking Preview in the designer tool bar. The preview compiles the report in the background and fills it with data retrieved by the query through the JDBC connection. As shown in Figure 13, the detail band repeats for every row in the query results, creating a simple table report.

    常见问题:

    iReport 是图形界面编辑 JasperReport 的工具,在简体中文的操作系统下,它的本地化功能把界面弄得又有中文又有英文,很乱。 以前的旧版可以在选项中方便地修改界面成英文,但是到了 iReport-nb-3.5.2 版在 iReport 安装路径下的 etc/ireport.conf 里增加启动参数,把这行 default_options="-J-Xms256m -J-Xmx512m -J-Dfile.encoding=UTF-8 -J-Dorg.netbeans.ProxyClassLoader.level=1000" 改成 default_options="-J-Xms256m -J-Xmx512m -J-Dfile.encoding=UTF-8 -J-Dorg.netbeans.ProxyClassLoader.level=1000 -J-Duser.language=en" 再启动就成英文界面了。 原理在于,通常咱们简体中文的操作系统下,JVM 会检测到系统属性 user.language=zh,而 iReport 启动时就使用这个系统属性值,我用 -J-Duser.language=en 指定了 iReport 启动时的参数,把用户语言明确为英文,界面就成英文的了。

    出现如上错误,在下图配置你预浏览的应用程序。

    至于更深入的自己去网上找吧,网上有很多。

     

    下面来进入JasperReport和struts的整合。

    Usage

    To use this plugin, have your packages that contain the target actions extend the provided jasperreports-default package, which contains the jasper result type. Then, simply use the result type in the desired actions. The result takes the following parameters:

    Generates a JasperReports report using the specified format or PDF if no format is specified.

    location (default) - the location where the compiled jasper report definition is (foo.jasper), relative from current URL. dataSource (required) - the EL expression used to retrieve the datasource from the value stack (usually a List). parse - true by default. If set to false, the location param will not be parsed for EL expressions. format - the format in which the report should be generated. Valid values can be found in JasperReportConstants. If no format is specified, PDF will be used. contentDisposition - disposition (defaults to "inline", values are typically filename="document.pdf" ). documentName - name of the document (will generate the http header Content-disposition = X; filename=X.[format] ). delimiter - the delimiter used when generating CSV reports. By default, the character used is ",". imageServletUrl - name of the url that, when prefixed with the context page, can return report images. reportParameters - (2.1.2+) OGNL expression used to retrieve a map of report parameters from the value stack. The parameters may be accessed in the report via the usual JR mechanism and might include data not part of the dataSource, such as the user name of the report creator, etc. exportParameters - (2.1.2+) OGNL expression used to retrieve a map of JR exporter parameters from the value stack. The export parameters are used to customize the JR export. For example, a PDF export might enable encryption and set the user password to a string known to the report creator. connection - (2.1.7+) JDBC Connection which can be passed to the report instead of dataSource 实际上我们只用3个,就是location (default) 、dataSource (required) 、format ,example:<result name="success" type="jasper"> <param name="location">foo.jasper</param> //jasper文件存放的位置,相对于webroot <param name="dataSource">mySource</param>//action文件执行后传出来的值list或者i                                                                  // mylst,相当于iReport中的fields <param name="format">PDF</param> </result>//输出格式

    Our Person class

    We start by defining a simple Person POJO class.

    com.acme.test.Person.java

    package com.acme.test; public class Person { private Long id;//这里要注意,你的iReport中定义了几个fields这里的值和它们对应, 不能多也不能少,而且名字要一样 private String name; private String lastName; public Person() { } public Person(String name, String lastName) { this.name = name; this.lastName = lastName; } public Person(Long id, String name, String lastName) { this.id = id; this.name = name; this.lastName = lastName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

    JasperReports libraries

    Before we can continue, we need to add the JR libraries to our classpath. You can download the JR project here: http://www.sourceforge.net/projects/jasperreports Save the jasperreports-X-project.zip to your harddisk, and extract the files.

    We need the following files:

    dist/jasperreports-X.jar lib/commons-*.jar (all the commons - except maybe for commons-logging) //经试验,                                                                             //commons-logging也必须引入。lib/itext-X.jar lib/jdt-compiler.jar

    Copy these jars over to your S2_WEBAPP/WEB-INF/lib directory, and add them to your classpath.

    Creating the Action

    com.acme.test.action.JasperAction

    package com.acme.test.action; import java.util.ArrayList; import java.util.List; import net.sf.jasperreports.engine.JasperCompileManager; import com.acme.test.Person; import com.opensymphony.xwork.ActionSupport; public class JasperAction extends ActionSupport { /** List to use as our JasperReports dataSource. */ private List<Person> myList; public String execute() throws Exception { // Create some imaginary persons. Person p1 = new Person(new Long(1), "Patrick", "Lightbuddie"); Person p2 = new Person(new Long(2), "Jason", "Carrora"); Person p3 = new Person(new Long(3), "Alexandru", "Papesco"); Person p4 = new Person(new Long(4), "Jay", "Boss"); // Store people in our dataSource list (normally they would come from a database). myList = new ArrayList<Person>(); myList.add(p1); myList.add(p2); myList.add(p3); myList.add(p4); // Normally we would provide a pre-compiled .jrxml file // or check to make sure we don't compile on every request. try { JasperCompileManager.compileReportToFile( "our_jasper_template.jrxml的绝对路径", "our_compiled_template.jasper的绝对路径"); } catch (Exception e) { e.printStackTrace(); return ERROR; } return SUCCESS; } public List<Person> getMyList() { return myList; } }

    Our JasperAction creates a list of several People. The JasperCompileManager compiles the jrxml template to a .jasper file.

    Our Jasper template

    JR uses XML configuration to define templates which are compiled to .jasper files. These templates define the resulting report. This is a handwritten version - for more complex versions I seriously suggest taking a look a the various GUI designers.

    our_jasper_template.jrxml

    <?xml version="1.0"?> <!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport name="jasper_test"> <!-- Our fields from the Person class. --> <field name="name" class="java.lang.String"/> <field name="lastName" class="java.lang.String"/> <title> <band height="50"> <staticText> <reportElement x="0" y="0" width="180" height="15"/> <textElement/> <text><![CDATA[Struts 2 JasperReports Sample]]></text> </staticText> </band> </title> <pageHeader> <band/> </pageHeader> <columnHeader> <band height="20"> <staticText> <reportElement x="180" y="0" width="180" height="20"/> <textElement> <font isUnderline="true"/> </textElement> <text><![CDATA[NAME]]></text> </staticText> <staticText> <reportElement x="360" y="0" width="180" height="20"/> <textElement> <font isUnderline="true"/> </textElement> <text><![CDATA[LASTNAME]]></text> </staticText> </band> </columnHeader> <detail> <band height="20"> <textField> <reportElement x="180" y="0" width="180" height="15"/> <textElement/> <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression> </textField> <textField> <reportElement x="360" y="0" width="180" height="15"/> <textElement/> <textFieldExpression><![CDATA[$F{lastName}]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band/> </columnFooter> <pageFooter> <band height="15"> <staticText> <reportElement x="0" y="0" width="40" height="15"/> <textElement/> <text><![CDATA[Page:]]></text> </staticText> <textField> <reportElement x="40" y="0" width="100" height="15"/> <textElement/> <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression> </textField> </band> </pageFooter> <summary> <band/> </summary> </jasperReport>

    To use the JasperReports result type we must either (a) extend the jasperreports-default package.

    所以我们可以把struts.xml中包引用写成

    <package name="default" namespace="/" extends="struts-default,jasperreports-default">

    直接用“,”来加入jasperreports-default(以后其他引入也同样)。

    将程序部署到tomcat上,然后运行。在地址栏输入“http://localhost:8080/TestJasperReport/myJasperTest.action ”就可以看到PDF文档了。


    最新回复(0)