Products Docs & Support Community

>> More Visual Web Pack Documentation

Generating Reports and PDFs From a Web Application

May [Revision number: V5.5.1-1]    

When you need to generate a report, a chart, or a PDF file from a web application, you have many third-party products to help you accomplish your task, including the open source JasperReports framework. JasperReports is a reporting tool that outputs reports in HTML, PDF, XLS, CSV, and XML formats. This tutorial show how to integrate the JasperReports framework into a web application that you build using the NetBeans Visual Web Pack.

In this tutorial, you create a web application that displays and prints information from a travel database. The web application lets you view a trip report in either HTML format or PDF format.

Contents

Creating a JasperReports Library
Setting Up the JRXML Editing Environment
Creating the Project
Setting Up the Report Resources
Mapping the JasperReports ImageServlet
Adding the Report Generation Logic
Creating the Database Query
Creating the Trip Report Page
 

JavaServer Faces Components/
Java EE Platform
works with1.2 with Java EE 5*
works with1.1 with J2EE 1.4
Travel Database requiredRequired
BluePrints AJAX Component Library not requiredNot required

* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.

This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the supported servers and Java EE platform, see the Release Notes.

Creating a JasperReports Library

Before you begin building your project, use the IDE's Library Manager to make the JasperReports Java reporting library easily available for any project.
  1. Download jasperreports-1.3.0-project.zip from and extract the files. You must register with JasperForge before you can download the zip file.

    Note: The examples in this tutorial use JasperReports 1.3.0 and the associated JAR files that are provided with that version. If you use a different version, the JAR library names and version numbers might vary. In addition, the list of JAR libraries to add might differ.
  2. In the IDE, choose Tools > Library Manager from the main menu.
  3. Click New Library, type JasperReports130 in the Library Name text box, and click OK.
  4. Click Add JAR/Folder and navigate to the directory into which you extracted the jasperreports-1.3.0-project.zip files.
  5. Navigate to the dist directory, select jasperreports-1.3.0.jar and press Enter.
  6. Click Add JAR/Folder again, and navigate into the ../lib directory (go up one directory and down into the lib directory).
  7. Use Ctrl-Click to select the following JAR files and press Enter. If you are using a different version than 1.3.0, consult the JasperForge web site to determine which JAR files to select.

    • commons-beanutils-1.7.jar
    • commons-collections-2.1.jar
    • commons-digester-1.7.jar
    • commons-logging-1.0.2.jar
    • itext-1.3.1.jar
    These are the minimum libraries that you need for a web application that uses the JasperReports framework. You might need to add additional libraries to use more advanced features. For example, if you are using the subreports feature, you might need to add commons-javaflow-20060411.jar.
  8. Verify that you have added the six libraries, as shown in the following figure.


    Figure 1: Library Manager Window Showing the JasperReports130 Library
  9. To make the JavaReports Javadoc available to the Java Editor, click the Javadoc tab, click Add ZIP/Folder, navigate to the directory into which you extracted the jasperreports-1.3.0-project.zip files, select the dist/javadoc subdirectory, and press Enter.
  10. (Optional) If you want to step into JasperReport classes during a debugging session, click the Sources tab, click Add JAR/Folder, navigate to the directory into which you extracted the jasperreports-1.3.0-project.zip files, select the src subdirectory, and press Enter.
  11. Click OK to close the Library Manager.

Setting Up the JRXML Editing Environment

You write your JavaReport templates in XML format. To enable the IDE's editor to recognize a JavaReport XML file (JRXML) as an XML file, you use the Options dialog to add jrxml to the Extensions and MIME Types property for the XML object, as shown in the following figure.


Figure 2: Associating a JRXML file with XML Objects
  1. Choose Tools > Options to open the Options dialog box.
  2. Click Advanced Options.
  3. Expand IDE Configuration, expand System, expand Object Types, and select XML Objects (not XML Schemas).
  4. Click the ellipsis (...) button for the Extensions and MIME Types property to open the customizer editor.
  5. Type jrxml in the Item text box and click Add.
  6. Click OK and close the Options dialog box.

Creating the Project

Complete the following steps to create and set up the project.
  1. In the Runtime window, expand the Databases node.
  2. Right-click the jdbc node for the Travel database and choose Connect from the pop-up menu.

    If the Travel database is not available, see the Configuration Information section in the NetBeans Visual Web Pack Installation Instructions for information.
  3. In the Connect dialog box appears, enter travel for the Password and select Remember Password During This Session.
  4. From the IDE main menu, choose File > New Project.
  5. In the New Project Wizard, select Web from the Categories list and select Visual Web Application from the Projects list.
  6. Click Next.
  7. Name the project TravelReport.
  8. Select the desired Server and Java EE Version, and click Finish.

    Your project appears with the initial page (Page1) open in the Visual Designer.

    Note that if you use a server other than the Sun Java System Application Server, you must make the database driver available to the server. See the Visual Web Project Configuration section of the Installation Guide for more information.

  9. In the Projects window, right-click TravelReport > Libraries and choose Add Library.
  10. In the Add Library window, select JasperReports130 as shown in the following figure, and click Add Library.


    Figure 3: Adding the JasperReports130 Library

Setting Up the Report Resources

In this section, you add an images directory and put the company's logo in this directory. Next, you add a JRXML template for the trip report, and you modify the project's build file to compile the JRXML template into a Jasper binary report template.

The JRXML template generates a report like the one shown in the following figure.


Figure 4: Trip Report
  1. In the Projects window, expland Web Pages.
  2. Right-click the resources node and choose New > Folder.
  3. Type images in the Folder Name text box and press Enter.
  4. Right-click the following image and use your browser's command for saving the image to your disk. Save the image in the path-to-web-project/TravelReport/web/resosurces/images folder.


    Figure 5: Company Logo
  5. Click the Files header, which appears next to the Projects header, to view the Files window.
  6. In the Files window, expand TravelReport.
  7. Right-click the src node and choose New > Folder.
  8. Type reports in the Folder Name text box.
  9. Ensure that the Parent Folder is set to src and press Enter.
  10. In the Files window, right-click TravelReport, and select Properties.
  11. In the Categories pane, select Sources.
  12. Click the Add Folder button that appears to the right of the Source Package Folders list.
  13. Navigate into the src folder, select reports, and click Open.
  14. In the Label text box for the src/reports row, change the value to JasperReports Definitions and press Enter.

    If you do not press Enter, the IDE does not save the changes.
  15. Click OK.
  16. Click the Projects header and notice the new JasperReports Definition node, which has a <default package> subnode.

    In the next step, you put a report definition in this default package. Later, you modify the build script to compile the report definitions in this folder into the build/web/WEB-INF/reports folder, which is where the runtime code in ApplicationBean1 expects to find them.
  17. Right-click the the JasperReports Definition node, and choose New > File/Folder.
  18. Select Other in the Categories panel, select Empty File in the File Types panel, and click Next.
  19. Type TripReportByPerson.jrxml in the File Name text box and press Enter. The new file opens in the XML editor.
  20. Copy the following XML tags and and paste into the empty XML file.

    Code Sample 1: JasperReport Template TripReportByPerson.jrxml
    <?xml version="1.0"?>
    <!DOCTYPE jasperReport
      PUBLIC "-//JasperReports//DTD Report Design//EN"
    <jasperReport name="TripReportByPerson">
    <style name="Arial_Normal" isDefault="true" fontName="Arial" fontSize="12"
      isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"
      pdfFontName="Helvetica" pdfEncoding="Cp1252" isPdfEmbedded="false"/>
    <style name="Arial_Bold" fontName="Arial" isDefault="false"  isBold="true"
      pdfFontName="Helvetica-Bold"/>
    <style name="Arial_Header1"  fontName="Arial" isDefault="false" fontSize="22"
      isBold="true" pdfFontName="Helvetica-Bold"/>
    <style name="Arial_Bold_White" fontName="Arial" forecolor="white"
      isDefault="false" fontSize="12" isBold="true" pdfFontName="Helvetica-Bold"/>
    <parameter name="LogoURL" class="java.net.URL"/>
    <field name="NAME" class="java.lang.String"/>
    <field name="TRIPID" class="java.lang.Integer"/>
    <field name="DEPDATE" class="java.util.Date"/>
    <field name="DEPCITY" class="java.lang.String"/>
    <field name="DESTCITY" class="java.lang.String"/>
    <field name="DESCRIPTION" class="java.lang.String"/>
    <group name="PersonGroup" minHeightToStartNewPage="84">
      <groupExpression>
      <![CDATA[$F{NAME}]]>
      </groupExpression>
      <groupHeader>
        <band height="64">
          <textField>
            <reportElement style="Arial_Bold" mode="Opaque" x="0" y="24"
              width="550" height="15" backcolor="#e0e0e0" />
            <textFieldExpression class="java.lang.String">
              <![CDATA["Scheduled Trips for " + $F{NAME}]]>
            </textFieldExpression>
          </textField>
        <line>
          <reportElement x="0" y="39" width="550" height="1" />
          <graphicElement />
        </line>
        <frame>
          <reportElement x="0" y="40" width="550" height="20"
            mode="Opaque" backcolor="lightGray"/>
          <staticText>
            <reportElement style="Arial_Bold_White" x="20" y="2" width="130" height="15"  />
            <text><![CDATA[Departure Date]]></text>
          </staticText>
          <staticText>
            <reportElement style="Arial_Bold_White" x="150" y="2" width="130" height="15"  />
            <text><![CDATA[Departure City]]></text>
          </staticText>
          <staticText>
            <reportElement style="Arial_Bold_White"  x="280" y="2" width="130" height="15" />
            <text><![CDATA[Destination City]]></text>
          </staticText>
          <staticText>
            <reportElement style="Arial_Bold_White" x="410" y="2" width="130" height="15" />
            <textElement textAlignment="Left" />
            <text><![CDATA[Purpose]]></text>
          </staticText>
          </frame>
        </band>
      </groupHeader>
    </group>
    <pageHeader>
      <band height="94">
        <image>
          <reportElement x="0" y="0" width="441" height="60"/>
          <graphicElement/>
          <imageExpression class="java.net.URL">
            <![CDATA[$P{LogoURL}]]>
          </imageExpression>
        </image>
        <line>
          <reportElement x="0" y="60" width="550" height="1"/>
          <graphicElement/>
        </line>
        <staticText>
          <reportElement style="Arial_Header1" x="0" y="60" width="445" height="30" />
          <text><![CDATA[Trip Report by Employee]]></text>
        </staticText>
      </band>
    </pageHeader>
    <detail>
      <band height="20">
        <textField pattern="dd/MM/yyyy">
          <reportElement x="20" y="0" width="100" height="20"/>
          <textFieldExpression class="java.util.Date">
            <![CDATA[$F{DEPDATE}]]>
          </textFieldExpression>
        </textField>
        <textField isBlankWhenNull="true">
          <reportElement x="150" y="0" width="100" height="20"/>
          <textFieldExpression class="java.lang.String">
            <![CDATA[$F{DEPCITY}]]>
          </textFieldExpression>
        </textField>
        <textField isBlankWhenNull="true">
          <reportElement x="280" y="0" width="100" height="20"/>
          <textFieldExpression class="java.lang.String">
            <![CDATA[$F{DESTCITY}]]>
          </textFieldExpression>
        </textField>
        <textField isBlankWhenNull="true">
          <reportElement x="410" y="0" width="100" height="20"/>
          <textFieldExpression class="java.lang.String">
            <![CDATA[$F{DESCRIPTION}]]>
          </textFieldExpression>
        </textField>
      </band>
    </detail>
    </jasperReport>
  21. Close and save the file.
  22. In the Files window, expand TravelReport, and double-click build.xml to open it in the editing area.
  23. Add the following script before the </project> tag.

    The script overrides the -post-compile target, which the IDE calls after it compiles the Java sources. The target script compiles any JRXML file found in the src/reports folder and puts the compiled report in the build/WEB-INF/reports folder.

    Code Sample 2: build.xml Report Compilation Script
        <!-- Customize the following property to point to the folder
             in which you unpacked your Jasper Reports release -->
        <property name="jrc.home"
                  value="JasperReports-Install-Dir/jasperreports-1.3.0"/>
        <!-- Define the classpath used for report compilation -->
        <path id="jrc.classpath">
            <fileset dir="${jrc.home}/dist"
                         includes="*.jar"/>
            <fileset dir="${jrc.home}/lib"
                         includes="*.jar"/>
        </path>
        <!-- Define the custom Ant task that compiles report definitions -->
        <taskdef name="jrc"
                 classname="net.sf.jasperreports.ant.JRAntCompileTask">
            <classpath refid="jrc.classpath"/>
        </taskdef>
        <!-- Define the target that will compile reports, after Java compiles
             have been completed -->
        <target name="-post-compile"
                        description="Compile all Jasper Reports Definitions">
            <!-- Create the output directory first -->
            <mkdir dir="${build.web.dir}/WEB-INF/reports"/>
            <!-- Compile report definition -->
            <jrc srcdir="src/reports"
                      destdir="${build.web.dir}/WEB-INF/reports">
                <classpath
                    refid="jrc.classpath"/>
                <include
                    name="*.jrxml"/>
            </jrc>
            <!-- Omit the report definition sources from the webapp -->
            <delete>
                <fileset dir="${build.web.dir}/WEB-INF/classes"
                         includes="*.jrxml"/>
            </delete>
        </target>
    
  24. Modify the value of the jrc.home property to point to the folder into which you unpacked the JasperReports zip file.
  25. Close and save the file.
  26. Choose Build > Build Main Project to invoke the build.xml script.
  27. In the Files window, expand build > web > WEB-INF > reports, and verify that the IDE generated the TripReportByPerson.jasper binary.

    If you see build errors in the Output window, or if the binary was not created, verify that you correctly set the jrc.home property in the build.xml file.

Mapping the JasperReports ImageServlet

The JasperReports framework includes a servlet named ImageServlet for displaying images in generated HTML reports. Even if you do not include images in your report, you must add a mapping for this servlet, because JasperReports uses blank images for spacing.

Complete the following steps to map the image URI to ImageServlet. You use the image URI later when you add code to export the report to HTML.
  1. In the Files window, expand web > WEB-INF, and double-click the web.xml node to open it in the XML editor.

    Make sure you edit the web.xml file under web > WEB-INF, and not the one under build > web > WEB-INF. If you edit the web.xml under build > web > WEB-INF, you will lose your changes the next time you build the project.
  2. In the editing toolbar, click Servlets to open the Servlet Editor.
  3. In the Servlets editor, click Add Servlet Element.

    The Add Servlet dialog box appears as shown in the following figure.

    Figure 6: Add Servlet Dialog Box
  4. In the Add Servlet dialog box, type the following values and click OK.

    Text Box Value
    Servlet Name   ImageServlet
    Servlet Class   net.sf.jasperreports.j2ee.servlets.ImageServlet
    URL Patterns   /image
  5. Close web.xml and save the changes.

    Now, the application knows that when it receives a request that is addressed to image, the application should send the request to the ImageServlet instance.

Adding the Report Generation Logic

Follow these steps to add logic to the application bean for generating the report.
  1. In the Projects window, double-click the Application Bean node to open ApplicationBean1.java in the editing area.
  2. Add the following code to the end of the file before the final end brace.

    Code Sample 3: Report Generation Code
    /**
     * <p>Prefix to the resource name for compiled reports.</p>
     */
    private static final String PREFIX = "/WEB-INF/reports/";
    /**
     * <p>Suffix to the resource name for compiled reports.</p>
     */
    private static final String SUFFIX = ".jasper";
    /**
     * <p>Valid content types for reports that we can produce.</p>
     */
    private static final String[] VALID_TYPES =
    { "text/html",            // Standard HTML representation
      "application/pdf",      // Adobe Portable Document Format
    };
    /**
     * <p>Generate the specified report, in the specified output
     * format, based on the specified data.</p>
     *
     * @param name Report name to be rendered
     * @param type Content type of the requested report ("application/pdf"
     *  or "text/html")
     * @param data <code>ResultSet</code> containing
     *  the data to report
     *
     * @exception IllegalArgumentException if the specified
     *  content type is not recognized
     * @exception IllegalArgumentException if no compiled report definition
     * for the specified name can be found
     */
    public void jasperReport(String name, String type,
                             ResultSet data) {
        jasperReport(name, type, data, new HashMap());
    }
    /**
     * <p>Generate the specified report, in the specified output
     * format, based on the specified data.</p>
     *
     * @param name Report name to be rendered
     * @param type Content type of the requested report ("application/pdf"
     *  or "text/html")
     * @param data <code>ResultSet</code> containing the data to report
     * @param params <code>Map</code> of additional
     *   report parameters
     *
     * @exception IllegalArgumentException if the specified
     *  content type is not recognized
     * @exception IllegalArgumentException if no compiled report definition
     * for the specified name can be found
     */
    public void jasperReport(String name, String type,
            ResultSet data, Map params) {
        // Validate that we recognize the report type
        // before potentially wasting time filling the
        // report with data
        boolean found = false;
        for (int i = 0; i < VALID_TYPES.length; i++) {
            if (VALID_TYPES[i].equals(type)) {
                found = true;
                break;
            }
        }
        if (!found) {
            throw new IllegalArgumentException("Invalid report type '"
                    + type
                    + "' requested");
        }
        // Look up the compiled report design resource
        ExternalContext econtext = getExternalContext();
        InputStream stream = econtext.getResourceAsStream(PREFIX + name
                    + SUFFIX);
        if (stream == null) {
            throw new IllegalArgumentException("Unknown report name '"
                    + name
                    + "' requested");
        }
        try {
            data.beforeFirst();
        } catch (Exception e) {
            throw new FacesException(e);
        }
        // Fill the requested report with the specified data
        JRResultSetDataSource ds = new JRResultSetDataSource(data);
        JasperPrint jasperPrint = null;
        try {
            jasperPrint = JasperFillManager.fillReport(
                stream, params, ds);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                ;
            }
        }
        // Configure the exporter to be used, along with the custom
        // parameters specific to the exporter type
        JRExporter exporter = null;
        HttpServletResponse response = (HttpServletResponse)
        econtext.getResponse();
        FacesContext fcontext = FacesContext.getCurrentInstance();
        try {
            response.setContentType(type);
            if ("application/pdf".equals(type)) {
              exporter = new JRPdfExporter();
              exporter.setParameter(JRExporterParameter.JASPER_PRINT,
                jasperPrint);
              exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                response.getOutputStream());
            } else if ("text/html".equals(type)) {
              exporter = new JRHtmlExporter();
              exporter.setParameter(JRExporterParameter.JASPER_PRINT,
                jasperPrint);
              exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,
                response.getWriter());
              // Make images available for the HTML output
              HttpServletRequest request =
                (HttpServletRequest)
                fcontext.getExternalContext().getRequest();
              request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);
              exporter.setParameter(
                JRHtmlExporterParameter.IMAGES_MAP, new HashMap());
              // The following statement requires mapping /image
              // to the imageServlet in the web.xml.
              //
              // This servlet serves up images including the px
              // images for spacing.
              //
              // Serve up the images directly so we
              // don't incur the extra overhead associated with
              // with a JSF request for a non-JSF entity.
              exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
                request.getContextPath() + "/image?image=");
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        }
        // Enough with the preliminaries ...
        // export the report already
        try {
            exporter.exportReport();
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new FacesException(e);
        }
        // Tell JavaServer Faces that no output is required
        fcontext.responseComplete();
    }
  3. Right-click in the source and choose Fix Imports from the pop-up menu. In the Fix Imports dialog box, verify that java.io.InputStream appears in the Fully Qualified Name field for the InputStream class, and that java.sql.ResultSet appears in the Fully Qualified Name field for the ResultSet class.
  4. Click OK.
  5. Close and save the file.

Creating the Database Query

In this application, you use the same database query result set for the trip information to display on the web page and in the generated report. You use the Query Editor to design the database query, as shown in the following figure.


Figure 7: Query Editor Settings for the Trip Result Set
  1. In the editing area, click the Page1 tab to view the page in the Visual Designer.
  2. In the Runtime window, expand Databases, expand the jdbc node for the Travel database, and expand Tables.
  3. Drag the TRIP node and drop it on a blank spot on the page.
  4. In the Outline window, expand SessionBean1 and double-click tripRowSet to open the Query Editor.
  5. In the TRIP table in the top panel, clear the checkboxes for PERSONID, TRIPTYPEID, and LASTUPDATED.
  6. Drag the PERSON node from the Servers window and drop it next to the TRIP table in the top panel.
  7. In the PERSON table, clear the checkboxes for PERSONID, JOBTITLE, FREQUENTFLYER, and LASTUPDATED.
  8. Drag the TRIPTYPE node from the Servers window and drop it next to the PERSON table in the top panel.
  9. In the TRIPTYPE table, clear the checkboxes for TRIPTYPEID, NAME, and LASTUPDATED.
  10. In the NAME row for the TRAVEL.PERSON table in the grid panel, choose Ascending from the drop-down list in the Sort Type column.

    The IDE sets the Sort Order to 1.
  11. In the DEPDATE row for the TRAVEL.TRIP table in the grid panel, choose Ascending from the drop-down list in the Sort Type column.

    The IDE sets the Sort Order to 2.
  12. Close the Query Editor for the tripRowSet.

Creating the Trip Report Page

In this section you add a table to Page1 to display the trip data, and you add buttons to generate the report in HTML and PDF formats, as shown in the following figure.


Figure 8: Page1
  1. Display Page1 in the Visual Designer.
  2. Drag the Table component from the Palette and drop it on the page.
  3. Right-click the Table component and choose Table Layout from the pop-up menu.
  4. In the Table Layout dialog box, choose tripDataProvider from the Get Data From drop-down list.
  5. Select PERSON.NAME in the Selected list and click the Up button repeatedly until PERSON.NAME moves to the top of the list.
  6. Click the Options tab.
  7. Type Trips in the Title text box.
  8. Select Enable Pagination.
  9. Click OK to close the dialog box.
  10. Drop a Button component above the Table component, type View Report, and press Enter.
  11. In the Properties window, set the id property to viewReportBtn.
  12. Click the ellipsis (...) button for the action property, choose viewReportBtn_action from the drop-down list, and click OK.
  13. Drop a Button component next to the View Report button, type Create PDF, and press Enter.
  14. In the Properties window, set the id property to createPdfBtn.
  15. Click the ellipsis (...) button for the action property, choose createPdfBtn_action from the drop-down list, and click OK.
  16. Double-click the View Report button to display the Java source for the viewReportBtn_action method.<
  17. Add the following code shown in bold to the body of the viewReportBtn_action method.

    Code Sample 4: viewReportBtn_action Method
        public String viewReportBtn_action() {
            // Free up the rowset resources
            tripDataProvider.close();
            Map fillParams = new HashMap();
            // The above statement generates warnings with Java SE 1.5
            // To eliminate the warnings, replace with the
            // following statement:
            // Map<String, URL> fillParams =
            //   new HashMap<String, URL.>>();
            try {
                fillParams.put
                  ("LogoURL",
                   getExternalContext().getResource("/resources/images/logo.gif"));
                getApplicationBean1().jasperReport
                  ("TripReportByPerson", "text/html",
                   getSessionBean1().getTripRowSet(), fillParams);
            } catch (Exception e) {
                log("Exception generating report", e);
                error("Exception generating report: " + e);
            }
            return null;
        }
    
  18. Scroll to the createPdfBtn_action method and add the following code shown in bold.

    Code Sample 5: createPdfBtn_action Method
        public String createPdfButton_action() {
            // Free up the rowset resources
            tripDataProvider.close();
            Map fillParams = new HashMap();
            try {
                fillParams.put
                  ("LogoURL",
                   getExternalContext().getResource("/resources/images/logo.gif"));
                getApplicationBean1().jasperReport
                  ("TripReportByPerson", "application/pdf",
                   getSessionBean1().getTripRowSet(), fillParams);
            } catch (Exception e) {
                log("Exception generating report", e);
                error("Exception generating report: " + e);
            }
            return null;
        }
    
  19. Right-click in the source and choose Fix Imports from the pop-up menu.
  20. In the main toolbar, click Run Main Project to build, deploy, and run the web application.
  21. In the web application, click View Report to view the report in HTML format.

    If you see broken images, open web > WEB-INF > web.xml and make sure that the entry for the ImageServlet exists. Sometimes, the IDE does not save the newly added entries.
  22. Click the Back button and click Create PDF to view the report in PDF format.

Summary

The major steps for using the JasperReports framework from a NetBeans Visual Web Pack project are as follows:
  1. Download and unzip the JasperReports framework.
  2. Use the Library Manager to create a JasperReports library. This makes it easy to add the necessary JasperReports JAR files to a web application.
  3. To add the JasperReports library to a web application, right-click the Library node in the Projects window, and choose Add Library.
  4. Use the Extensions and MIME Types property for XML Objects in the Options dialog box to add jrxml to the list of XML objects. By doing so, the IDE will open jrxml files in the XML editor.
  5. Add a mapping to net.sf.jasperreports.j2ee.servlets.ImageServlet in the web.xml file.
  6. Add logic to the application bean for generating the reports.
  7. After creating the report, call facesContext.responseComplete( ) to terminate the current request lifecycle.
  8. If you are generating an HTML report, use the IMAGES_URI parameter to pass the URI for the ImageServlet class. For example, if you set the URI to /image, set the IMAGES_URI parameter to request.getContextPath() + "/image?image=".
  9. You can use a cached rowset, such as the cached rowset that the IDE creates when you add a dataprovider to a page, as a datasource for filling the report. Be sure to call the dataprovider's close method before filling the report.

See Also:

  • "JasperReports for Java Developers" by David R. Heffelfinger.
  • JasperReports Documentation Page
  • Integrating and Using JasperReports in NetBeans

This page was last modified:  May 24,