JasperReports 3.5 for Java Developers- P2

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
76
lượt xem
26
download

JasperReports 3.5 for Java Developers- P2

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'jasperreports 3.5 for java developers- p2', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: JasperReports 3.5 for Java Developers- P2

  1. Chapter 3 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: Parameter Description JasperReport This is used as the report template. Instances of net. jasperReport sf.jasperreports.engine.JasperReport are in-memory representations of compiled report templates. String destFileName This is used to define the name of the destination file in which to save the report. Map parameters This is an instance of a class implementing the java.util. Map interface. It is used to initialize all the report parameters defined in the report template. Connection connection This is used to connect to a database in order to execute an SQL query defined in the report template. JRDataSource dataSource This is an instance of a class implementing the net. sf.jasperreports.engine.JRDataSource interface. 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 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. [ 39 ]
  2. Creating your First Report Although report templates containing an embedded SQL query are easier to develop, passing an instance of JRDataSource has an advantage. That is, the same 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(); } } } [ 40 ]
  3. Chapter 3 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". Previews and compiles our First Report [ 41 ]
  4. Creating your First Report After executing the new ANT target view, we should see a window similar to the following: [ 42 ]
  5. Chapter 3 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; [ 43 ]
  6. Creating your First Report import net.sf.jasperreports.engine.JasperRunManager; public class FirstReportSendToBrowserServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) 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. [ 44 ]
  7. Chapter 3 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: [ 45 ]
  8. Creating your First Report Elements of a JRXML report template In the previous example, we used the element of the JRXML report template to generate a report displaying some static text. The element is used to display the main section of the report. However, JRXML templates can contain many other sections that allow us to display secondary data on the report or to do some other tasks, such as importing Java packages and controlling how the data is displayed in the report. The following sections cover all the subelements of the root element. Unless stated otherwise, each element can be used any number of times in the template. This element is used for putting arbitrary information in the report template. Properties can be retrieved by a Java application that is loading the report by invoking the JasperReport.getProperty() method. [ 46 ]
  9. Chapter 3 This element is used for importing individual Java classes or complete packages. The report styles can be defined in separate report templates to allow these styles to be reused across the reports. This mechanism is similar to the way cascading stylesheets can be defined in separate CSS files when dealing with HTML. Report style templates can be defined in XML files, which are conventionally saved in JRTX files or, more infrequently, in an instance of a class implementing the net.sf.jasperreports.engine.JRTemplate interface. "my_template.jrtx" This element is used for styling report elements, setting the font style, size, background color, foreground color, and so on. Most other report elements have a style attribute that can be used to specify their style. The element has an isDefault attribute that can be used to specify that the style being defined is the default style, and should be used when other elements don't specify their style attribute. The element can be used to provide data indirectly in the report to charts and crosstabs in the report template. [ 47 ]
  10. Creating your First Report Subdatasets need to be referenced by a crosstab or chart. This element is used to define report parameters. Parameter values are supplied through a java.util.Map parameter by calling the appropriate methods in the JasperReports API. This element is used to define an SQL query to obtain data from a database. A JRXML template can contain zero or one element. This element is required if we wish to embed an SQL query in the report template. This element is used to map data from datasources or queries to report templates. Fields can be combined in report expressions to obtain the necessary output. This element is used to sort the data in the report by the field specified in this element's name attribute. Sorting can be ascending or descending, as specified in the order attribute. If no order is specified, the default is ascending. A JRXML template can have one or more elements corresponding to fields in the report template. [ 48 ]
  11. Chapter 3 The report expressions used several times in a report can be assigned to the variables to simplify the template. $F{FieldName} This element is used to filter out the datasource records from the report. If the expression nested inside the element resolves to Boolean.TRUE, the current row in the datasource is included in the report. If it resolves to Boolean.FALSE or null, the current row is not included in the datasource. Please note that this element is primarily meant to be be used when our datasource type cannot be filtered trivially, such as when we use a CSV file datasource. A report template can contain zero or one element. This element is used to group the consecutive records in a datasource that share some common characteristics. [ 49 ]
  12. Creating your First Report This element is used to define the page background for all the pages in the report. It can be used to display images or text and is very useful to display watermarks. "image.gif" This element cannot be used more than once in a JRXML template. This is the report title. It appears only once at the beginning of the report. This element defines a page header that is printed at the beginning of every page in the report. [ 50 ]
  13. Chapter 3 A JRXML template can contain zero or one element. This element defines the contents of column headers. It is ignored if the report has a single column. If present, the number of elements in the template must match the number of columns. This element defines the detail section of the report. The content of the section is repeated for each record in the report's datasource. [ 51 ]
  14. Creating your First Report A JRXML template can contain zero or one elements. Most report templates contain a element; typically, this is where the main data of the report is displayed. This element defines the contents of column footers. It is ignored if the report has a single column. A JRXML template can contain zero or more elements. If present, the number of elements in the template must match the number of columns. This element defines a page footer that is printed at the bottom of every page in the report. A JRXML template can contain zero or one element. [ 52 ]
  15. Chapter 3 Data defined in this element is displayed as the page footer of the last page rather than the footer defined in the element. A JRXML template can contain zero or one element. This element is printed once at the end of the report. A JRXML template can contain zero or one element. [ 53 ]
  16. Creating your First Report The element can be used to control what will be generated in the report when the datasource contains no data. Just like the element, most elements discussed in the previous sections contain a single element as its only child element. We will discuss the specific subelements of the element in later chapters. In the following screenshot, we can see a report that can help us visualize the relative position of the report sections: [ 54 ]
  17. Chapter 3 As we can see, the page footer is labeled Page Footer/Last Page Footer. If the JRXML template for the report contains a element, its contents will be displayed in the last page of the report, instead of the contents of the element. It is worth mentioning that if our report has only one page, and the report template contains both the and the elements, then in that case the contents of will be displayed as the footer of the first (and only) page; the value of the element will never be displayed. Before we move on, we should mention that the and elements will be displayed on the report only if it has more than one column. How to add columns to a report is discussed in detail in Chapter 6, Report Layout and Design. Summary In this chapter, we learned to create a JRXML report template by editing an XML file. We also saw how to preview the template by using the tools supplied by JasperReports. We understood how to compile a JRXML template programmatically and by using a custom ANT task. After the successful compilation of the report, we filled the report template with data by calling the appropriate methods supplied by the JasperFillManager class, and we viewed the generated reports in native JasperReports' format by using the JasperViewer utility. The chapter also guided us through the different report sections in a JRXML template. Finally, we created web-based reports by displaying generated reports in a web browser. We are now ready to move on to the next chapter. [ 55 ]
  18. Creating Dynamic Reports from Databases In the previous chapter, we learned how to create our first report. The simple report in the previous chapter contained no dynamic data. In this chapter, we will explore how to create a report from the data obtained from a database. In this chapter, we will cover the following topics: • How to embed SQL queries into a report template • How to pass rows returned by an SQL query to a report through a datasource • How to use report fields to display data obtained from a database • How to display database data in a report by using the element of the JRXML template Datasource definition A datasource is what JasperReports uses to obtain data for generating a report. Data can be obtained from databases, XML files, arrays of objects, collections of objects, and XML files. In this chapter, we will focus on using databases as a datasource. The next chapter discusses the other types of datasources.
  19. Creating Dynamic Reports from Databases Database for our reports We will use a MySQL database to obtain data for our reports. The database is a subset of public domain data that can be downloaded from http://dl.flightstats.us. The original download is 1.3 GB, so we deleted most of the tables and a lot of data to trim the download size considerably. MySQL dump of the modified database can be found as part of this book's code download at http://www.packtpub.com/files/ code/8082_Code.zip. The flightstats database contains the following tables: • aircraft • aircraft_models • aircraft_types • aircraft_engines • aircraft_engine_types The database structure can be seen in the following diagram: aircraft aircraft_types tail_num char(6)NOT NULL (PK) aircraft_type_id tinyint unsigned(3) NOT NULL (PK) aircraft_serial char(20) NOT NULL description char(30) NOT NULL aircraft_model_code char(7) NOT NULL aircraft_engine_code char(5) NOT NULL year_built year(4) NOT NULL aircraft_type_id tinyint unsigned(3) NOT NULL aircraft_models aircraft_engine_type_id tinyint unsigned(3) NOT NULL aircraft_model_code char(7) NOT NULL (PK) registrant_type_id tinyint unsigned(3) NOT NULL manufacturer char(30) NOT NULL name char(50) NOT NULL model char(20) NOT NULL address1 char(33) NOT NULL aircraft_type_id tinyint unsigned(3) NOT NULL address2 char(33) NOT NULL aircraft_engine_type_id tinyint unsigned(3) NOT NULL city char(18) NOT NULL aircraft_category_id tinyint unsigned(3) NOT NULL state char(2) NOT NULL amateur tinyint unsigned(3) NOT NULL zip char(10) NOT NULL engines tinyint(4) NOT NULL region char(1) NOT NULL seats smallint(6) NOT NULL county char(3) NOT NULL weight int(11) NOT NULL country char(2) NOT NULL speed smallint(6) NOT NULL certification char(10) NOT NULL status_code char(1) NOT NULL mode_s_code char(8) NOT NULL fract_owner char(1) NOT NULL aircraft_engines last_action_date date(10) NOT NULL aircraft_engine_code char(5) NOT NULL (PK) cert_issue_date date(10) NOT NULL manufacturer char(10) NOT NULL air_worth_date date(10) NOT NULL model char(13) NOT NULL aircraft_engine_type_id tinyint unsigned(3) NOT NULL horsepower mediumint unsigned(8) NOT NULL aircraft_engine_types thrust mediumint unsigned(8) NOT NULL aircraft_engine_type_id tinyint unsigned(3) NOT NULL (PK) fuel_consumed decimal(10,2) NOT NULL description char(30) NOT NULL [ 58 ]
Đồng bộ tài khoản