官术网_书友最值得收藏!

Generating the report

In JasperReports lingo, the process of generating a report from a report template or jasper file is known as filling the report. Reports are filled programmatically by calling the fillReportToFile() method in the net.sf.jasperreports.engine.JasperFillManager class. The fillReportToFile() method fills a report and saves it to disk.

There are six overloaded versions of the fillReportToFile() method, which are listed below:

  1. JasperFillManager.fillReportToFile( JasperReport jasperReport, String destFileName, Map parameters, Connection connection )
  2. JasperFillManager.fillReportToFile( JasperReport jasperReport, String destFileName, Map parameters, JRDataSource dataSource )
  3. JasperFillManager.fillReportToFile( String sourceFileName, Map parameters, Connection connection )
  4. JasperFillManager.fillReportToFile( String sourceFileName, Map parameters, JRDataSource dataSource )
  5. JasperFillManager.fillReportToFile( String sourceFileName, String destFileName, Map parameters, JRDataSource dataSource )
  6. JasperFillManager.fillReportToFile( String sourceFileName, String destFileName, Map parameters, JRDataSource datasource )

The following table illustrates the parameters used in these methods:

As can be seen above, in most cases, we pass data for filling reports using an instance of a class implementing the net.sf.jasperreports.engine.JRDataSource interface. The report templates can have embedded SQL queries. These SQL queries are defined inside the <queryString> element in the JRXML file. For reports that contain an SQL query, instead of passing a JRDataSource, we pass an instance of a class implementing the java.sql.Connection interface. JasperReports then uses this connection object to execute the query and obtain the report data from the database.

Although report templates containing an embedded SQL query are easier to develop, passing an instance of JRDataSource has an advantage. That is, thesame reports can be used with different datasources, such as databases, CSV files, Java objects, and so on. We will cover the database reports in the next chapter. Other datasources supported by JasperReports are covered in detail in Chapter 5, Working with Other Datasources.

Our report contains only static text. There is no dynamic data displayed in the report. There is no way to fill a report without passing either a JRDataSource or a Connection. JasperReports provides an implementation of the JRDataSource containing no data. The class is appropriately named JREmptyDataSource. As our report does not take any parameters, passing an empty instance of java.util.HashMap will be enough for our purposes. We will follow the recommended approach of naming our report using the same name as the one used for the report template (except for the extension). Given all of these facts, the most appropriate version of fillReportToFile() for our report is the fourth version. Here is its signature again:

JasperFillManager.fillReportToFile(String sourceFileName, Map parameters, JRDataSource dataSource)

The following Java class fills the report and saves it to disk:

package net.ensode.jasperbook;

import java.util.HashMap;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;

public class FirstReportFill
{
  public static void main(String[] args)
  {
    try
    {
      System.out.println("Filling report...");
      JasperFillManager.fillReportToFile("reports/FirstReport.jasper",
                                         new HashMap(),new JREmptyDataSource());
      System.out.println("Done!");
    }
    catch (JRException e)
    {
      e.printStackTrace();
    }
  }
}

After executing this class, we should have a file named FirstReport.jrprint in the same location as our compiled report template, which was named FirstReport.jasper.

Viewing the report

JasperReports includes a utility class called net.sf.jasperreports.view.JasperViewer, which can be used to view the generated reports. As with the tool to preview designs, the easiest way to use this utility is to wrap it around an ANT target. Again, this is the approach taken by the samples included with JasperReports, and the approach we will use here. Let's add a new target to our ANT build file. Following the conventions established by the JasperReports samples, we will name this target "view".

<project name="FirstReport XML Design Preview"default="viewDesignXML"basedir=".">

  <description>
    Previews and compiles our First Report
  </description>

  <property name="file.name" value="FirstReport" />
<!-- Directory where the JasperReports project file was extracted, 
     needs to be changed to match the local environment -->
  <property name="jasper.dir"value="/opt/jasperreports-3.5.2" />
  <property name="classes.dir" value="${jasper.dir}/build/classes" />
  <property name="lib.dir" value="${jasper.dir}/lib" />

  <path id="classpath">
    <pathelement location="./" />
    <pathelement location="${classes.dir}" />
    <fileset dir="${lib.dir}">
       <include name="**/*.jar" />
    </fileset>
  </path>

  <target name="viewDesignXML" 
          description="Launches the design viewer to preview the XMLreport design.">
    <java classname="net.sf.jasperreports.view.JasperDesignViewer"fork="true">
      <arg value="-XML" />
      <arg value="-F${file.name}.jrxml" />
      <classpath refid="classpath" />
    </java>
  </target>

  <target name="viewDesign" 
          description="Launches the design viewer to preview thecompiled report design.">
    <java classname="net.sf.jasperreports.view.JasperDesignViewer"fork="true">
      <arg value="-F${file.name}.jasper" />
      <classpath refid="classpath" />
    </java>
  </target>

  <target name="compile" 
          description="Compiles the XML report design and producesthe .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>

 <target name="view" 
 description="Launches the report viewer to preview thereport 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>
</project>

After executing the new ANT target view, we should see a window similar to the following:

Viewing the report

That's it! We have successfully created our first report.

Displaying reports in a web browser

In the previous section, we discussed how to create a report and save it to disk in JasperReports' native format. In this section, we will explain how to display a report in a web browser with the help of the servlet API. The following example demonstrates how to accomplish this:

package net.ensode.jasperbook;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;

public class FirstReportSendToBrowserServlet extends HttpServlet
{
  protected void doGet(HttpServletRequest request, HttpServletResponseresponse)
  throws ServletException, IOException
  {
    ServletOutputStream servletOutputStream = response.getOutputStream();
    InputStream reportStream =getServletConfig().getServletContext().getResourceAsStream("/reports/FirstReport.jasper");

    try
    {
 JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream,new HashMap(),new JREmptyDataSource());
      response.setContentType("application/pdf");
      servletOutputStream.flush();
      servletOutputStream.close();
    }
    catch (JRException e)
    {
    // display stack trace in the browser
      StringWriter stringWriter = new StringWriter();
      PrintWriter printWriter = new PrintWriter(stringWriter);
      e.printStackTrace(printWriter);
      response.setContentType("text/plain");
      response.getOutputStream().print(stringWriter.toString());
    }

  }
}

Because web browsers are incapable of displaying reports in JasperReports' native format (at least without the help of an applet), we must export the report to a format the browser can understand. JasperReports allows us to export reports to PDF and many other formats. As PDF is one of the most popular formats, we chose it as the export format in this example.

The servlet in the last example calls the static JasperRunManager.runReportToPdfStream() method. The signature for this method is as follows:

runReportToPdfStream(java.io.InputStream inputStream,java.io.OutputStream outputStream,java.util.Map parameters,JRDataSource jrDataSource)

To display the report in the browser, we need to pass the binary report template or jasper file, in the form of a stream, as the first argument to this method. We can accomplish this by calling the javax.servlet.ServletContext.getResourceAsStream() method, passing a string containing the location of the jasper file as a parameter. This method will return an instance of java.io.InputStream, which can be used as the first argument for the JasperRunManager.runReportToPdfStream() method.

The JasperRunManager.runReportToPdfStream() method needs an instance of java.io.OutputStream() to write the compiled report. We can simply use the default output stream for the servlet, which can be obtained by calling the javax.servlet.http.HttpServletResponse.getOutputStream() method.

The next two arguments for the JasperRunManager.runReportToPdfStream() method are a java.util.Map and a datasource. The former is used to pass any parameters to the report and the latter to pass data in the form of a net.sf.jasperreports.engine.JRDataSource. We are not passing any parameters or data to this simple report, hence an empty HashMap and JREmptyDataSource suffice.

To ensure that the browser displays the report properly, we must set the content type to application/pdf. We can accomplish this by calling the javax.servlet.http.HttpServletResponse.setContentType() method.

The resulting code for this example needs to be deployed to a servlet container. An ANT script to automate this process can be found as part of the code download for this book, which can be found at http://www.packtpub.com/files/code/8082_Code.zip. The following screenshot shows the report being displayed as a PDF in a browser:

Displaying reports in a web browser
主站蜘蛛池模板: 闽清县| 阿拉善左旗| 罗江县| 芦溪县| 平原县| 大余县| 祁门县| 鞍山市| 临泽县| 紫云| 平乐县| 华容县| 瓦房店市| 宁南县| 荣成市| 连平县| 泽州县| 屯昌县| 青海省| 徐汇区| 淮南市| 安乡县| 潮安县| 浪卡子县| 南通市| 张家界市| 城步| 农安县| 镇江市| 固镇县| 甘德县| 城固县| 来凤县| 耒阳市| 宁化县| 西乌珠穆沁旗| 长汀县| 本溪市| 柞水县| 邵阳市| 将乐县|