Jasperreport+ireport practical operation and Web application

Source: Internet
Author: User
Tags lowercase prepare
Jasperreport+ireport practical operation and Web applicationAfter studying Jasperreports+ireport, I felt deeply, not only mastered the report development technology, but also mastered how to generate PDF,XLS,RTF files in the Web, the following is the Jasperreports+ireport development knowledge points:
1. Fields, variables, parameters, arguments
2. Vector images, bitmaps
3. Hyperlinks, anchors
4. Data source, custom data source
5. Internationalization (i18n)
6. Scripts
7. subreports
8. Chart (pie chart, bar chart, line chart)
9. Export Pdf,xls,html ...

Operating version:jasperreports2.0.2+ireport2.0.2 Description:This article is not an entry-level tutorial, so reading this article requires a certain foundation.
Here's how to do it in ireport, and how to deploy it in real-world projects, for each knowledge point. 1. Fields, variables, parameters, argumentsThis knowledge point is very simple, under the ireport View menu there are fields,variables,parameters three menus, if you want to define a parameter, you can do the following.
Click the Parameters menu, which pops up an action parameter window, click the New button, enter parameter name (Parameter name), select the parameter type (Parameter Class type), and if you want to assign a default value, fill in the default value expression Value Expression) (the default value, as a string, is filled in "string", such as in the form of a new Integer (1), and so on.), after filling out, click OK to create a new parameter.

Defining a field is the same as defining a parameter, and as far as defining the variable operation, it is relatively less used, and is not described here.

How do I refer to fields, variables, parameters in ireport?
Reference field using $F {field_name}
Reference variable using $V {variable_name}
Reference parameters use $P {param_name} or $P! {Param_name}
$P! {Param_name} is commonly used to stitch SQL statements, and its values can be spliced with SQL statements before executing the query.
Example: Define a parameter named where type is a string default value of "where id=100"
There is a query statement: SELECT * FROM user $P! {WHERE}
The query is executed as: SELECT * from user where id=100

There is also a special case when $P {param_name} is used in SQL statements.
Example: There is a parameter named ID, type is integer, the default value is new Integer (100)
There is a query statement: SELECT * from user where id= $P {ID}
The query is executed normally, but if there is a parameter named name, the type is string and the default value is "Zhanngle"
There is a query statement: SELECT * from user where name= $P {name}
Error executing query, do not know why (even if there is a record in the database), do not know whether it is a bug, or it is wrong. The workaround is to change the query statement to: SELECT * from user where name= ' $P! {Name} '
Can prove $p! {} syntax, only replace operation, as above will only $p! Replace {name} with Zhanngle.
It is also possible to prove the $p{} syntax, when used in SQL statements, where the value is a numeric type and can be performed normally, such as a string type error.

How do I send a parameter in a program?
As the previous example defines a name parameter, it is also very simple to query the program for different records in a dynamic way.
The program code is as follows:
MAP params = new HashMap ();
Params.put ("name", "Zhanngle");
Jasperprint print = Jasperfillmanager.fillreport (jasper, Params,conn);
is to put the parameter name and value put into a map and then populate the report with the map passed. 2. Vector images, bitmapsJasperReports supports vector and bitmap functions because he encapsulates the Jfreechart (Jfreechart is an open source graphics solution Library), uses ireport to draw vectors or inserts bitmaps, without us writing a line of code,   These jasperreports have been packaged for us all, ireport only provide three kinds of vectors, namely, rectangle, circle, line, the following first describes how to draw a vector diagram, and then how to insert a bitmap. Initial work: Create a new empty report first To draw a rectangle:Click on the toolbar's Rectangle button, in the detail area, draw a rectangle, the drawing method and Windows comes with the drawing tool, after drawing, right-click on the rectangle, select the properties, you can set the properties of the rectangle, you have to set up according to their own needs, such as setting the foreground color, Background color ... Drawing a circle is like drawing a line method, just the right circle tool or line tool at the toolbar point. It's simple. problem arises1. There can be no overlap between the diagram and the figure (more specifically, between elements and elements), such as overlapping to show only the topmost graph. 2. Using the line tool can draw a slash, when exported to PDF file, there is no problem, when exporting Html,xls file, found that the slash into a rectangle, the solution is: using external graphics editing software, draw a slash, and save as a picture file, and then insert the picture file in the corresponding location of the report. How to test preview Pdf,html,xls in ireport ... File?1. First of all to set up a PDF file what preview, HTML file with what preview ... Click Options---Settings, External Programs, fill out the correct external program in the popup window. My settings are as follows: External editor:c:/program files/editplus 2/editplus.exe (jrxml file editor) PDF Viewer:d:/program files/adobe/ Acrobat 7.0/reader/acrord32.exe HTML viewer:c:/program files/internet explorer/iexplore. EXE XLS Viewer: "D:/program files/microsoft office/office11/excel. EXE "RTF viewer:c:/program files/windows Nt/accessories/wordpad.exe This step is set once and no further setup is required. 2. Set what file you want to preview, ireport the default preview is a PDF file, but not using our prepared external program preview, but using JasperReports jrviewer preview. You can also preview the pdf file by setting up a preview using our prepared external program, click Build, PDF Preview, and then click the Execute (empty data source) button. Click Build, HTML Preview, and then click the Execute (empty data Source) button to view the HTML file. Note:Any report must have a data source to provide data for the report. Execute (empty data source) means to construct a data source that has only one record to pass to the report, and the value of this record is NULL, which is useful when testing a report that does not require data. Execute (whit active connection) means that the current active connection or data source is passed to the report and the report is generated. BitmapInserting a bitmap is also very simple, click the image button on the toolbar, and then draw a "rectangle" in the Detail area (same as the draw rectangle), at which point you can see a picture in the area you are drawing, right-click on the image, select Properties, select the Image tab, click the "Find ..." button, Select the picture you want to insert, OK, you can see the picture you want to insert. How do i insert a picture in a real project and change the picture dynamically?In the real project can not use the method described above to insert the picture, the above method is only to start to the role of Hello World, in order to insert a picture in the real project, you can be prepared according to the following methods.       1. Define a parameter named ImageName type: String has no default value of 2. In the report design interface, draw an image, open the Image's property box, select the Image tab, and in the Image Expression text box, enter: $P {imageName}, the path representing the picture is determined by the ImageName parameter value. We can pass the value of this parameter in the program. How do I pass in the parameter value in the program?The sample code is as follows: ServletContext context = Request.getsession (). Getservletcontext ();
MAP params = new HashMap ();
Params.put ("ImageName", Context.getrealpath ("/reports/test.jpg"));
Jasperprint print = Jasperfillmanager.fillreport (jasper, Params,conn); Change images dynamically by passing in different path values How do I display a picture in HTML?When exporting a report with pictures to the Pdf,xls file, there is no problem, but when exported to the HTML file, found that the picture does not display properly, do not worry, JasperReports has provided us with a solution. The steps to resolve are as follows: 1. Add the following code to the Web. xml file < servlet >
< Servlet-name > Jasperreportsimageservlet </servlet-name >
< Servlet-class > Net.sf.jasperreports.j2ee.servlets.ImageServlet </servlet-class >
</servlet >

< servlet-mapping >
< Servlet-name > Jasperreportsimageservlet </servlet-name >
< Url-pattern >/servlets/image </url-pattern >
</servlet-mapping > 2. The program code is written in the following manner ServletContext context = Request.getsession (). Getservletcontext ();
MAP params = new HashMap ();
Params.put ("ImageName", Context.getrealpath ("/reports/test.jpg"));
Map ImageMap = new HashMap ();
Request.getsession (). SetAttribute ("Images_map", ImageMap);

Jasperprint print = Jasperfillmanager.fillreport (jasper,params,conn);
Request.getsession (). SetAttribute (Net.sf.jasperreports.j2ee.servlets.ImageServlet.DEFAULT_JASPER_PRINT_SESSION _attribute,print);

Jrhtmlexporter exporter = new Jrhtmlexporter ();
Exporter.setparameter (Jrexporterparameter.jasper_print, PRINT);
Exporter.setparameter (Jrexporterparameter.output_writer, Response.getwriter ());
Exporter.setparameter (JRHTMLEXPORTERPARAMETER.IMAGES_MAP,IMAGEMAP);
Exporter.setparameter (Jrhtmlexporterparameter.images_uri, Request.getcontextpath () + "/servlets/image?image=");
Exporter.setparameter (Jrhtmlexporterparameter.is_remove_empty_space_between_rows, Boolean.TRUE);
Exporter.setparameter (Jrhtmlexporterparameter.is_using_images_to_align, boolean.true);
3. Hyperlinks, anchorsSometimes we want to add a hyperlink or anchor to a keyword in the report to jump to the page when the mouse clicks the keyword. For this small feature, JasperReports also provides support for easy operation in ireport. Not all elements support hyperlinks, At the moment I know that the common elements that support hyperlinks are the dynamic text box element (text Field), the bitmap element (Image), and the chart element. These three elements are the same way to set hyperlinks, so just describe how dynamic text boxes set up hyperlinks. How do i insert a hyperlink in ireport?Because static text boxes do not support hyperlinks, you can only set hyperlinks to static text through dynamic text boxes, as described in the following: 1. In the toolbar, select the Text field button, go back to the Detail area, draw a text field (as in the drawing rectangle method), and then in the text Right click on Field, select Edit expresion, enter the expression "CSDN" in the popup window, then click the Apply button. ( Note:"CSDN" to include double quotes) 2. Open the property box for the Text Field, select the Hyperlink tab, change the Hyperlink target to Blank,hyperlink Type to Reference, and the Hyperlink Ref Erence enter "Http://www.csdn.net" in the expression box, and then click Close. ( Note:"Http://www.csdn.net" to include double quotes) at this time a hyperlink has been set, export pdf,html file to see, click Csdn can pop up csdn page. How do I insert an anchor in a ireport?In fact, the anchor is a special form of hyperlinks, so supporting the elements of the hyperlink support anchors, elements that do not support hyperlinks do not support anchors, anchor settings are very simple, as long as you know the use of HTML <a> set anchor, then ireport is similar. Setting an anchor is also a two-step operation 1. Set the Anchor object to draw a dynamic text box in the Title area, enter the expression "2007 year-end financial statement", then open its Hyperlink tab, enter "Title" in the Anchor Name expression box, and click Close. This An anchor object has been defined. Its anchor name is title. 2. Link Anchor object draw a dynamic text box in the detail area, enter the expression "back to top", then open its Hyperlink tab, change Hyperlink target to Self,hyperlink Type to Localanchor, In the Hyperlink Anchor expression box, enter "title" and click Close. A chain has been set up, export pdf,html look, of course, if your report is not much content, then the anchor does not play any role. 4. Data source, custom data sourceThe data source, as its name implies, is where the report data comes from. JasperReports can get data from databases, XML files, CSV files, java.util.Collection objects, and custom data sources. In the real project, the report data is generally obtained from the database, the following describes how to prepare the data source of the connection database in ireport. The procedure is as follows: Description:This example creates a new document (report document) with a MySQL database to prepare the data source, point data, Connections/data Sources, New, Database JDBC Connection, Next. In the popup window, follow the prompts to fill in the properties, example: Name:mysql, jdbc Driver:com.mysql.jdbc.Driver jdbc Url:jdbc:mysql://localhost:3306/db_name User Name:root Password:your_password fill out, click the Test button, such as pop-up Connection test successful!, the data source is configured correctly, and then click the Save button to save the configuration. Otherwise the configuration error, please check where an error occurred. Once prepared, you can connect to the database. then how to query the database with the data source and display the query results on the report. Description:In this case, the database data source must be prepared for normal operation. And there are tables in the connected database. In the popup window, enter the SQL query statement: SELECT * from T_users. If the SQL statement correctly displays all the fields of the table at the bottom of the window, click OK to complete the report query work. You can look at the fields panel, ireport has automatically defined all the fields that were queried as field objects (that is, the definition field that was first mentioned). After saying how to query the data, the next task is how to display the data on the report interface. Point View---Fields open the field panel, select any one of the columns on the panel, drag it to the upper-left corner of the detail area, and select a field to drag to the upper-middle corner of the detail area, so you can experiment with two fields, as long as the detail area is wide enough, You can drag two more fields into the detail area, and the fields dragged to the detail area will be displayed in the report. Adjust the height of the detail area, run (Build-and-Execute (whit active connection)) Look, if you see the right data, congratulations, you've done your experiment. Custom Data SourcesSometimes, you may need to customize a data source to meet your needs, and JasperReports also provides good support. As long as you implement the Jrdatasource interface, it's OK, it's easy. The Jrdatasource interface is declared as follows: public interface Jrdatasource
... {
public Boolean Next () throws Jrexception;
Public Object GetFieldValue (Jrfield Jrfield) throws
Jrexception;
}
The following I am a custom data source code: 1.   First, create a bean class, the Bean Class property is all uppercase, because ireport automatically define the field when the field name is all uppercase, you can also manually change to lowercase, then the Bean Class property can be lowercase, you want to ensure that the Bean Class property name and field name consistent (including case). Package test;
Import Java.sql.Timestamp;

Publicclass Bean ... {
Privateintid;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.