Jasperreport + ireport practice operations and web applications

sponsored links
Jasperreport + ireport practice operations and web applications

To learn End jasperreports + ireport, for I feel deeply, not only mastered the technical report development, but also how the web master to generate pdf, xls, rtf file, the following is the development of knowledge points jasperreports + ireport:
1. Fields, variables, parameters, pass parameters
2. Vector, bitmap
3. Hyperlinks, anchor
4. Data sources, custom data sources
5. Internationalization (I18N)
6. Script
7. Subreport
8. Chart (pie chart, column chart, line graph)
9. Export pdf, xls, html ...

Operation Version: jasperreports2.0.2 + ireport2.0.2
Description: This is not an entry-level tutorial, so read this article requires a foundation.
The following for each knowledge point, explaining how in the ireport is, and how to deploy in real projects.
1. Fields, variables, parameters, pass parameters to this knowledge is as simple as the view menus in ireport under Fields, Variables, Parameters of three menus, such as to define a parameter, can proceed as follows.
Click the Parameters menu, and then pop up a window of operating parameters, click the New button, enter the parameter name (Parameter Name), select the parameter type (Parameter Class Type), if we assigned a default value of fill in the default expression (Default Value Expression) (default value if the string The "string" forms fill in, such as plastic Zeyi new Integer (1) the application form, and so on.), fill it out, tap OK to a new parameter.

Custom Fields and definition of parameters is the same operation, The operation is almost the definition of variables, but also relatively less certain, not described here.

How to reference fields in ireport, variables, parameters?
Reference field using $ F (field_name)
Reference variable to use $ V (variable_name)
Reference parameter using $ P (param_name) or $ P! (Param_name)
$ P! (Param_name) are generally used for stitching sql statement, its value can be spliced with the sql statement, after deciding on the implementation of the query.
Example: define a parameter of type String named where the default value of "where"
A query: select * from user $ P! (Where)
The implementation of the query will be replaced with: select * from user where

$ P (param_name) used in the sql statement, there is also a special case.
Example: there is a parameter named id, of type Integer, the default value is new Integer (100)
A query: select * from user where $ P (id)
Implementation of the query can be normal query, but if there is a parameter called name, type String, default is "zhanngle"
A query: select * from user where name = $ P (name)
Implementation of the query error, do not know why (even if the database record in the section), I do not know is not a bug, or where their own mistake. The solution is, the query to: select * from user where name = '$ P ! (name) '
Can prove that $ P! () Syntax, only do replacement operations, above only the $ P! (Name) replaced zhanngle.
Can also prove that $ P () syntax to use in the sql statement, the value of digital type can also be normal execution, such as a string type will be wrong.

How to pass parameters in the program?
As patients defines a name parameter, then the dynamic in the program how to pass parameter query different records, we are also very simple.
Code is as follows:

Map params = new HashMap ();
params.put ("name", "zhanngle");
JasperPrint print = JasperFillManager.fillReport (jasper, params, conn);
Is the parameter name and value put into a map, and then filled statements will pass past the line of the map.
2. Vector, bitmap
Jasperreports support vector and bitmap features, because he encapsulates jfreechart (jfreechart is an open source graphics solutions library), using ireport draw vector or bitmap insertion, can not we write a line of code, which has been for us jasperreports All packages Well, ireport only three vectors, namely, rectangular, circular, line, the following describes how to draw the first vector, and then how to insert a bitmap.

Initial work: first create a new empty statements draw the rectangle: Click the Rectangle button on the toolbar, in the Detail area, draw a rectangle, drawing methods and drawing tool that comes with windows, like drawing is completed, right click on the rectangle, choose property, you can set the properties of the rectangle, we can set up according to their needs, such as setting the foreground color, background color ...
Draw circle with method of drawing the same line, only the corresponding point in the tool bar round tool or line tool on the line.
It is very simple.

Problems
1. Between the chart and graph (a more specific statement should be between elements and elements) can not have any overlap, duplication can only be displayed if the top chart.
2. Using the line tool to draw the diagonal, when the export to pdf file without any problem, when exporting html, xls file, found in a slash into a rectangle, the solution is: use an external graphics editor, draw a diagonal and saved as image files, then the image files into the corresponding location in the report.
How to test in ireport preview pdf, html, xls ... paper?
1. First of all, to set about what the preview pdf file, html file what preview ...
Point Options -> Settings -> External Programs, fill in the pop-up window outside the correct procedures.
If 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
The one-step operation as long as the settings later on do not need to set up.
2. Set what you want to preview documents, ireport preview the pdf file by default, but it is not prepared to use our external program preview, but the use jasperreports the JRViewer preview. You can also set the external use of our preparation program to preview, point Build -> PDF Preview, and then point Execute (empty data source) button, you can preview the PDF file. Point Build -> HTML Preview, and then point Execute (empty data source) button, you can preview the HTML file.
Note: A report must have a data source to provide data for the report.
Execute (empty data source), which means that only one record to construct a data source to pass reports, and record this value is null, the button is not required in the test report data, very useful.
Execute (whit active connection), which means that the current active connection or data source to pass reports, and generate reports.

Bitmap bitmap into very simple, click the Image button on the toolbar, and then draw in the Detail area a "rectangle" (Draw rectangle with the same operation), this time in your area to see a picture drawn in this picture right click, select Properties, choose Image tab, and point "Find ..." button, select the picture you want to insert, OK, you can see you want to insert pictures.

In real projects how to insert images, dynamic change picture?
In real projects can not use the method described above to insert the picture, the above method is the role of Kai to hello world, in order to insert a picture in a real project, can be prepared in accordance with the following methods.
1. Define a parameter named imageName type: String default value is not
2. In the report design interface, draw a Image, open the Image of the property box, select Image tab, in the Image Expression text box, enter: $ P (imageName), represent the image of the path is the parameter value by the imageName decision, we can pass the parameters in the program's value.
How to pass the parameters in the program worth it?
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);
Different values can be introduced dynamically change the image path

How to display images in html?
When exporting a report with a picture to pdf, xls file, there is no problem, but when exported to html file and found that picture can not be shown, do not rush, jasperreports has provided us with solutions. Resolved 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. Program code 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, anchor and sometimes we would like to add a keyword report for a hyperlink or anchor, so the mouse click on the keyword jump page. For this small feature, jasperreports also provided support to operate in ireport very simple. Not all elements support hyperlinks, now I know the common elements to support hyperlinks, the dynamic text box element (Text Field), the bitmap element (Image), the chart elements (Chart tool). These three element method to set the hyperlink is the same, only describes how to set the dynamic text box to a hyperlink.

How to insert hyperlinks in ireport?
As the static text box does not support hyperlinks, so only through the dynamic text box set for the static text hyperlinks, methods of operation as follows:
1. In the toolbar select the Text Field button to return to Detail area, draw a Text Field (the same way as with the drawing rectangle), then right click on the Text Field, select Edit Expresion, in the pop-up window, enter the expression " CSDN ", and then point apply button. (Note:" CSDN "to include the double quotes)
2. To open the Text Field properties box, select Hyperlink tab, Hyperlink target to blank, Hyperlink Type to Reference, in the Hyperlink Reference Expression box, enter "http://www.csdn.net", then point Close. (Note: "http://www.csdn.net" to include the double quotes)
At this point a hyperlink has been set up, export pdf, html file and see, you can click the pop-up CSDN CSDN website.

How to insert anchor in ireport?
In fact, the hyperlink anchor is a special form, and therefore supported the hyperlink anchor support element, the element does not support hyperlinks do not support anchors, anchor set is also very simple, as long as you know the <a> setting anchors using html , then the ireport is similar.
Set the anchor, two steps need to
1. Set the anchor object to draw a dynamic region in the Title text box, enter the expression "year-end 2007 financial statements", and then open it's Hyperlink tab, in the Anchor Name Expression box, enter the "title", was closed. At this point have been defines an anchor object. It is the anchor name is title.
2. Link anchor objects in the Detail area to draw a dynamic text box, enter the expression "back to the top" and then open it's Hyperlink tab, Hyperlink target to self, Hyperlink Type to LocalAnchor, in the Hyperlink Anchor Expression box Enter the "title", was closed.
An anchor link has been set up, export pdf, html to see, of course, if you report the content limited, then the anchor not have any effect.

4. Data sources, custom data source data source data source name suggests, the report data come from. jasperreports from database, XML file, CSV file, java.util.Collection objects and custom data sources are data. In the real project, the report data generally get from the database, the following describes how to prepare to connect ireport system database data source. Follow these steps:

Note: this example to MySql database for the preparation of the data source to create a new Document (Report Form), Point Data -> Connections / Data Sources -> New -> Database JDBC Connection -> Next. In the popup window follow the prompts to complete the property, example:
Name: mysql,
JDBC Driver: com.mysql.jdbc.Driver
JDBC URL: jdbc: mysql: / / localhost: 3306/db_name
User Name: root
Password: your_password

Completed, click the Test button, such as pop-up Connection test successful!, Prepared on behalf of the data source is correct, and then point Save button to save preparation. Otherwise, preparation error, check what went wrong.
Good preparation, you can connect to the database.
So how do you query the database with the data source and query results appear in the report to?
Description: The operation must be prepared well in this case the data source database to normal operation. And database connections to have the table.
Point Data -> Report Query, in the pop-up window, enter SQL query: select * from t_users.
If the sql statement is correct in the bottom of the window shows all the fields in the table, click OK, the report query to complete the work.
We can look at the Fields panel, ireport have automatically check out all the fields, defined as a field object (that is, what the definition of top field).
That said, check out how the data, the next task is how the data is displayed in the report interface.
Point View -> Fields Open Fields panel, the panel on the Choose a field, drag it to the top left corner alignment Detail region, then select a field onto the Detail area of the corner, well on the use of the word section of a test on it, as long as the Detail area enough width, you can drag the two fields to the Detail over the region, drag the Detail area of the field will be displayed in the report. Detail adjust the height of the region, run (Build -> Execute (whit active connection)) click to see it, if you see the correct data, then Congratulations, you test a success!

Sometimes custom data source, you may need to customize a data source to meet your needs, jasperreports have also provided good support.
As long as you realize JRDataSource interface, on the line, is very simple now!
JRDataSource interface, the following statement:
public interface JRDataSource
... (
public boolean next () throws JRException;
public Object getFieldValue (JRField jrField) throws
JRException;
)
The following is my custom I have a data source:
1. First create a Bean class, the bean class attribute are all uppercase, because ireport automatically defined fields, field names are all uppercase, you can also manually changed to lowercase, so that the bean class attribute can be lower case, you To ensure that the bean class attribute names and field names the same (including case).

package test;
import java.sql.Timestamp;

publicclass Bean ... (
privateintID;
private String NAME;
private String NICKNAME;
privateintSCORE;
privatefloatBALANCE;
private Timestamp LASTLOGINDATE;

publicfloat getBALANCE () ... (
returnBALANCE;
)
publicvoid setBALANCE (float balance) ... (
this.BALANCE = balance;
)
publicint getID () ... (
returnID;
)
publicvoid setID (int id) ... (
this.ID = id;
)
public Timestamp getLASTLOGINDATE () ... (
returnLASTLOGINDATE;
)
publicvoid setLASTLOGINDATE (Timestamp lastLoginDate) ... (
this.LASTLOGINDATE = lastLoginDate;
)
public String getNAME () ... (
returnNAME;
)
publicvoid setNAME (String name) ... (
this.NAME = name;
)
public String getNICKNAME () ... (
returnNICKNAME;
)
publicvoid setNICKNAME (String nickname) ... (
this.NICKNAME = nickname;
)
publicint getSCORE () ... (
returnSCORE;
)
publicvoid setSCORE (int score) ... (
this.SCORE = score;
)
)
2. Create a data source implementation class
package test;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

publicclass TestBeanDataSource implements JRDataSource ... (

private List list;
privateintindex =- 1;

public TestBeanDataSource () ... (
list = new ArrayList ();
Bean bean = null;

for (int i = 0; i <100; i + +) ... (
bean = new Bean ();
bean.setID (i);
bean.setNAME ("name" + i);
bean.setNICKNAME ("nickname" + i);
bean.setBALANCE ((float) (Math.random () * 100 * i));
bean.setSCORE (i * 2);
bean.setLASTLOGINDATE (new Timestamp (System.currentTimeMillis ()));
list.add (bean);
)
)
publicboolean next () throws JRException ... (
return + + index <list.size ();
/ / Return false;
)

public Object getFieldValue (JRField field) throws JRException ... (
Bean bean = (Bean) list.get (index);
String fieldName = field.getName ();

try ... (
return PropertyUtils.getProperty (bean, fieldName);
) Catch (Exception e) ... (
thrownew JRException (e);
)
)
public List getList () ... (
returnlist;
)
publicvoid setList (List list) ... (
this.list = list;
)

)
3. Fill the DataSource in the statements went on the line pass.
JasperPrint print = JasperFillManager.fillReport (jasper, map, new TestBeanDataSource ());
JRHtmlExporter exporter = new JRHtmlExporter ();
...
exporter.setParameter (JRExporterParameter.JASPER_PRINT, print);
...
exporter.exportReport ();
At this point the source of report data is from a custom data source are 100 records.

How to prepare ireport support custom data sources?
1. The above two classes is created, they still create a factory class, for the production of custom data sources, the factory class code is as follows:
package test;

import net.sf.jasperreports.engine.JRDataSource;

publicclass TestCustomJRDataSourceFactory ... (
publicstatic JRDataSource test () ... (
returnnew TestBeanDataSource ();
)
)
2. As is the custom data source, so the data source reference to the relevant category, all introduced ireport the classpath, to call for ireport, ireport would otherwise throw java.lang.ClassNotFoundException, for example, I have three classes are on d: / workspace / jasperreports / classes directory, then point Options -> Classpath -> Add Folder options d: / workspace / jasperreports / classes, selected the options, point Save Classpath.
3. In ireport create a custom data source Data -> Connections / Data Sources -> New -> Custom JRDataSource
Will pop up a window, according prompted to fill in the content, for example:
Name: testCustom
Factory Class: test.TestCustomJRDataSourceFactory
The static method to call ...: test
Click Test, pop-up Connection test successful!, Represents the successful preparation of a custom data source, otherwise check for errors.
Completed the three steps, you can use in ireport the custom data source was.

How to activate the data source?
After the data source is created, ireport will automatically activate it, since the same time only one data source is active, so when you want to activate the other data source can be the following:
Point Data -> Set Active Connection, in the pop-up window, select the data source you want to activate, and then OK to activate the point.
Only activate the data source will be passed to report.

5. Internationalization (I18N)
International, also known as I18N, because English is the international Internationalization, it begins with I, N end, the middle 18 letters.
Jasprereports through ResourceBundle class support I18N.
How in the ireport prepared to support I18N?
We create a new report, the report called I18NTest, then Edit -> Internationalization -> Locale Files -> Create New Locale, enter _zh_CN, press OK, then create a support Chinese. Properties file, the file name of all its Write a I18NTest_zh_CN.properties, stored in a file in the same directory with the report, we have to build a support in English. properties files, click Create New Locale, enter _en, press OK. If you have some understanding of the ResourceBundle class, then you will know what is meant by the input.
Create a properties file, the next step is to edit them, in the Locale resource bundle window, double-click I18NTest_zh_CN.properties, then you can edit the properties of the file, we add one in the properties file i18n = Hey! International, and then save. Re-edit I18NTest_en.properties, in the properties file, add a i18n = hello I18n, save.
Operation that is well above the ireport prepared to support i18n.
How to call the document display properties?
Any region in the report can display the contents of a properties file called.
Call Syntax: $ R (key) or str (key)
Example: To call the above preparation of the property, using $ R (i18n) or str ("i18n")
Formatted message using the msg (pattern, arg1)
Cases: msg ("my name is (0 }."," zhannggle") is the output: my name is zhanngle.
msg () has three overloaded methods, msg (pattern, arg1), msg (pattern, arg1, arg1), msg (pattern, arg1, arg1, arg1)
Difference is a different parameter, the bottom through MessageFormat.format (pattern, arguments) implementation.
Use the properties file format message.
Case of a properties file is defined as follows:
a = jasperreports
b = ireport
hi = hello (0), hello (1)!

We can use the following expression displays the message
msg (str ("hi"), str ("a"), str ("b")) output: hello jasperreports, hello ireport!
How to store in the web development properties file?
The properties file stored in the WEB-INF/classes directory, jasprereports search it will go to this directory.
Tip: If preparing a good ireport support I18N, to the report file can be automatically stored directory to find a good property files by copying them to WEB-INF/classes directory on it.
[Discussion]: jasperreports by ResourceBundle.getBundle () Get properties file, but getBundle () There are three overloaded methods getBundle (baseName), getBundle (baseName, locale), getBundle (baseName, locale, loader)
I do not know which way jasperreports is used, if used first, then the default language for server systems based properties file, regardless of what language the client requests, such as the use of the second, three will be for the client request to acquire the language properties file. I was doing the test, regardless of what the client set the language, have returned to the server system default language, Yan depressed, I do not know where I am wrong, or jasperreports adopted the first way to obtain the properties file, no test out, Yan Unfortunately, to view the source to know.

6. Script script is a java class that is used to specify the details of implementation during printing. Some of the script method is call reporting engine, when some special cases, such as creating a new page or processing detail lines.
The realization of a script may inherit net.sf.jasperreports.engine.JRAbstractScriptlet class.
net.sf.jasperreports.engine.JRAbstractScriptlet statement as follows:
package net.sf.jasperreports.engine;
/ ** *//**
* @ Author Teodor Danciu (teodord@users.sourceforge.net)
* @ Version $ Id: JRDefaultScriptlet.java, v 1.3 2004/06/01 20:28:22
teodord Exp $
* /
public class JRDefaultScriptlet extends JRAbstractScriptlet
... (
public JRDefaultScriptlet () ... ()
public void beforeReportInit () throws JRScriptletException
... (
)
public void afterReportInit () throws JRScriptletException
... (
)
public void beforePageInit () throws JRScriptletException
... (
)
public void afterPageInit () throws JRScriptletException
... (
)
public void beforeColumnInit () throws JRScriptletException
... (
)
public void afterColumnInit () throws JRScriptletException
... (
)
public void beforeGroupInit (String groupName) throws
JRScriptletException
... (
)
public void afterGroupInit (String groupName) throws
JRScriptletException
... (
)
public void beforeDetailEval () throws JRScriptletException
... (
)
public void afterDetailEval () throws JRScriptletException
... (
)
)

How to prepare the script in ireport?
Ireport default does not use script, we can do the following to make it using a script.
First create a new report documents, statements were TestScriptlet
Then Edit -> Report Properties -> Scriptlet Class -> Use ireport internal scriptlet support
At this point ireport have used an internal definition of a good script, the script is fundamentally empty, does not implement any functionality.
We can also edit the script type, do the following:
Point Edit -> Scriptlet Editor, edit the script will pop up a window class, find the script constructor, the constructor method to add a statement: System.out.println ("create scriptlet ...");
In the constructor add a max following method, the code is as follows:
import net.sf.jasperreports.engine .*;

public class <ScriptletClassName> extends it.businesslogic.ireport.IReportScriptlet ... (

/ ** *//** Creates a new instance of JRIreportDefaultScriptlet * /
public <ScriptletClassName> () ... (
System.out.println ("create scriptlet ...");
)
public int max (int a, int b) ... (
if (a> = b) return a;
return b;
)
)
Save and then save that created a script, and then save the report file, then you can go to the report file directory to find a TestScriptleScriptlet the java file, which is ireport script automatically generated class files (the script class name = report name + Scriptlet ).
How to call the script in ireport?
In the report created jasperreports will automatically create the script object, and generating script, jasperreports script automatically calls the appropriate method of approach we need to customize the call manually before execution.
Cases above max method call, use the expression:
((TestScriptletScriptlet) $ P (REPORT_SCRIPTLET)). Max (23,64)
$ P (REPORT_SCRIPTLET) report script returns the current class you can call the script giving top priority to the above expression.
How web projects in the preparation of the script?
When using the script in the web project, the method can not be prepared in accordance with the above, and that would not find the script class. 4-step solution is as follows:
1. The lib directory in ireport find ireport.jar, it introduced to the project.
2. The ireport automatically generated src java files to the project directory (package too).
3. After compiling the project, the project's classes directory to the classpath in ireport.
4. Point Edit -> Report Properties -> Scriptlet Class -> Use this scriptlet class ..., in the following text box to enter the script class name, such as patched, to enter the package name, point OK, compile ireport.

7. Subreport to be continued ...

8. Chart (pie chart, column chart, line graph)
To be continued ...

9. Export pdf, xls, html ...
Here is what I export all kinds of statements Servlet source code for your reference!
package servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

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

import oracle.jdbc.driver.OracleDriver;
import test.TestBeanDataSource;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

publicclass ExportReportServlet extends HttpServlet ... (

/ ** *//**
* Destructionoftheservlet. <br>
* /
publicvoid destroy () ... (
super.destroy (); / / Just puts "destroy" string in log
/ / Put your code here
)

publicvoid doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ... (

String view = request.getParameter ("view");
if (view == null | | view.trim (). length () == 0) return;

if (view.equalsIgnoreCase ("html")) doHtml (request, response);
if (view.equalsIgnoreCase ("pdf")) doPdf (request, response);
if (view.equalsIgnoreCase ("xls")) doExcel (request, response);
if (view.equalsIgnoreCase ("xml")) doXml (request, response);
)
privatevoid doHtml (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ... (
ServletContext context = getServletContext ();
/ / String jrxml = context.getRealPath ("/ WEB-INF/reports/Test1.jrxml");
/**//*
try (
String jasper = context.getRealPath ("/ WEB-INF/reports/Test1.jasper");
String html = "/ reports /" + System.currentTimeMillis ()+". html ";
JasperRunManager.runReportToHtmlFile (jasper, context.getRealPath (html), new HashMap (), getConn ());

response.sendRedirect (request.getContextPath () + html);

) Catch (JRException e) (e.printStackTrace ();)
* /
String reportDir = context.getRealPath ("/ WEB-INF/reports");
String jasper = reportDir + "/ Test1.jasper";

response.setContentType ("text / html");
response.setCharacterEncoding ("utf-8");
Map map = new HashMap ();
Map imageMap = new HashMap ();
map.put ("exportType", "html");
map.put ("imageTest", context.getRealPath ("/ reports / star.gif"));
map.put ("SUBREPORT_DIR", reportDir +"/");
request.getSession (). setAttribute ("IMAGES_MAP", imageMap);
Connection conn = getConn ();
try ... (

/ / JasperPrint print = JasperFillManager.fillReport (jasper, map, new TestBeanDataSource ());
JasperPrint print = JasperFillManager.fillReport (jasper, map, conn);
/ / JasperPrint print = JasperFillManager.fillReport (jasper, map, new JREmptyDataSource ());
JRHtmlExporter exporter = new JRHtmlExporter ();

request.getSession (). setAttribute (ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, print);

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);

exporter.exportReport ();

) Catch (JRException e) ... (
StringWriter sw = new StringWriter ();
PrintWriter pw = new PrintWriter (sw);
e.printStackTrace (pw);

response.setContentType ("text / plain");
response.getOutputStream (). print (sw.toString ());
) Finally ... (
if (conn! = null)
try ... (
if (! conn.isClosed ()) conn.close ();
) Catch (SQLException e) ... (
e.printStackTrace ();
)
)
)
privatevoid doPdf (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ... (
ServletContext context = getServletContext ();
/ / String jrxml = context.getRealPath ("/ WEB-INF/reports/Test1.jrxml");
String reportDir = context.getRealPath ("/ WEB-INF/reports");
String jasper = reportDir + "/ Test1.jasper";

response.setContentType ("application / pdf");
Map map = new HashMap ();
map.put ("exportType", "pdf");
map.put ("imageTest", context.getRealPath ("/ reports / star.gif"));
map.put ("SUBREPORT_DIR", reportDir +"/");
Connection conn = getConn ();
try ... (
OutputStream os = response.getOutputStream ();
InputStream is = new FileInputStream (jasper);
JasperRunManager.runReportToPdfStream (is, os, map, conn);
/ / JasperRunManager.runReportToPdfStream (is, os, map, new TestBeanDataSource ());

os.flush ();
os.close ();
) Catch (JRException e) ... (
StringWriter sw = new StringWriter ();
PrintWriter pw = new PrintWriter (sw);
e.printStackTrace (pw);

response.setContentType ("text / plain");
response.getOutputStream (). print (sw.toString ());
) Finally ... (
if (conn! = null)
try ... (
if (! conn.isClosed ()) conn.close ();
) Catch (SQLException e) ... (
e.printStackTrace ();
)
)
)
privatevoid doExcel (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ... (
ServletContext context = getServletContext ();
String reportDir = context.getRealPath ("/ WEB-INF/reports");
String jasper = reportDir + "/ Test1.jasper";

response.setContentType ("application / vnd.ms-excel");
response.setHeader ("Content-Disposition", "attachment; filename = Test1.xls");
Map map = new HashMap ();
map.put ("exportType", "xls ");// set parameters, export type xls
map.put ("imageTest", context.getRealPath ("/ reports / star.gif "));// set the parameters, image path
map.put ("SUBREPORT_DIR", reportDir +"/");
Connection conn = getConn ();
try ... (
JasperReport report = (JasperReport) JRLoader.loadObject (jasper);
try ...{// set on margin, left margin, right margin, bottom margin to 0
java.lang.reflect.Field margin = JRBaseReport.class.getDeclaredField ("leftMargin");
margin.setAccessible (true);
margin.setInt (report, 0);
margin = JRBaseReport.class.getDeclaredField ("topMargin");
margin.setAccessible (true);
margin.setInt (report, 0);
margin = JRBaseReport.class.getDeclaredField ("rightMargin");
margin.setAccessible (true);
margin.setInt (report, 0);
margin = JRBaseReport.class.getDeclaredField ("bottomMargin");
margin.setAccessible (true);
margin.setInt (report, 0);
/ / Remove hidden lines in Excel, Tips
java.lang.reflect.Field pageHeight = JRBaseReport.class.getDeclaredField ("pageHeight");
pageHeight.setAccessible (true);
pageHeight.setInt (report, Integer.MAX_VALUE);

/ / Don't print group header on each page
if (null! = report.getGroups ())
... (
for (int i = 0; i <report.getGroups (). length; i + +)
... (
report.getGroups () [i]. setReprintHeaderOnEachPage (false);
)
)

) Catch (Exception e) ... (e.printStackTrace ();)

JasperPrint print = JasperFillManager.fillReport (report, map, conn); / / fill data
/ / JasperPrint print = JasperFillManager.fillReport (report, map, new TestBeanDataSource ());// fill data

JRAbstractExporter exporter = new JExcelApiExporter ();
exporter.setParameter (JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter (JRExporterParameter.OUTPUT_STREAM, response.getOutputStream ());
exporter.setParameter (JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
Boolean.TRUE); / / Remove blank lines
exporter.setParameter (JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); / / whether to produce a working table on each page
exporter.setParameter (JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); / / if blank background

exporter.exportReport ();

response.getOutputStream (). flush ();
response.getOutputStream (). close ();
) Catch (JRException e) ... (
StringWriter sw = new StringWriter ();
PrintWriter pw = new PrintWriter (sw);
e.printStackTrace (pw);

response.setContentType ("text / plain");
response.getOutputStream (). print (sw.toString ());
) Finally ... (
if (conn! = null)
try ... (
if (! conn.isClosed ()) conn.close ();
) Catch (SQLException e) ... (
e.printStackTrace ();
)
)
)
privatevoid doXml (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ... (
ServletContext context = getServletContext ();
/ / String jrxml = context.getRealPath ("/ WEB-INF/reports/Test1.jrxml");
String reportDir = context.getRealPath ("/ WEB-INF/reports");
String jasper = reportDir + "/ Test1.jasper";

response.setContentType ("text / xml");
Map map = new HashMap ();
map.put ("exportType", "xml");
map.put ("imageTest", context.getRealPath ("/ reports / star.gif"));
map.put ("SUBREPORT_DIR", reportDir +"/");
Connection conn = getConn ();
try ... (
JasperPrint print = JasperFillManager.fillReport (jasper, map, conn);
OutputStream os = response.getOutputStream ();
JasperExportManager.exportReportToXmlStream (print, os);
os.flush ();
os.close ();
) Catch (JRException e) ... (
StringWriter sw = new StringWriter ();
PrintWriter pw = new PrintWriter (sw);
e.printStackTrace (pw);

response.setContentType ("text / plain");
response.getOutputStream (). print (sw.toString ());
) Finally ... (
if (conn! = null)
try ... (
if (! conn.isClosed ()) conn.close ();
) Catch (SQLException e) ... (
e.printStackTrace ();
)
)
)
privatestatic Connection getConn () ... (
try ... (
Class.forName (OracleDriver.class.getName ());
return DriverManager.getConnection ("jdbc: oracle: thin: @ 202.192.xxx.xxx: 1521: orc92", "name", "password");
) Catch (Exception e) ... (
e.printStackTrace ();
)
returnnull;
)

/ ** *//**
* Initializationoftheservlet. <br>
*
* @ ThrowsServletExceptionifanerroroccure
* /
publicvoid init () throws ServletException ... (
/ / Put your code here
)

)

This article comes from CSDN blog, reproduced, please indicate the source: http://blog.csdn.net/zhanngle/archive/2007/12/31/2006013.aspx
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Jasperreport + ireport practice operations and web applications

  • Ruby sqlserver connection method

    The above code is, of course, incomplete and can certainly be improved and extended (error handling, etc.). But, hopefully, it provides you with a solid foundation on which to build. UPDATE: You might like to know that you can automate many of your S ...

  • Student candidates for software recommendations

    Financial crisis has come, the project got worse, employees are brothers, should not because there is no project, on vacation or dismissal. However, small businesses, how many did not make money, can only help each other to tide over the difficulties. As

  • ajax input prompt implementation

    Projects have used at the time entered by the user to give some tips, suggesting that the contents are extracted from the database (in Chinese). So a google search under the amended part of their code to share with you. Attachment is available at the ...

  • Rails source code analysis (4): Request / Response

    1) Rails defines two abstract class: AbstractRequest and AbstractResponse code is not posted, first take a look at Response. 2) is mainly responsible for the specific ctgi_process.rb main interface is responsible for implementation methods of impleme ...

  • JS charts extjs implementation tools can be combined

    OpenFlashChart brief introduction by valensoft 2009-1-10 8:29:00 OpenFlashChart is an open source Flash and Javascript to the technical foundation for the free chart, using it to create some very useful analysis of the effect of the statements of the char

  • Hibernate primary key strategy-sequence

    Today, the use of hibernate in the company encountered a troublesome problem, the use of hibernate when the primary key generation strategy set sequence, but always reported in the implementation could not get next sequence value of the error, then o ...

  • JDBC example of a long time do not have JDBC forgot

    A back-up here to stay. The first: The second:

  • Hibernate pessimistic locking mechanism for locking and optimistic locking

    hibernate lock mechanism 1. Pessimistic lock It refers to the modification of data by outsiders hold a conservative attitude. The assumption that at any time access to data, may also have another client to access the same data, in order to maintain t ...

  • In the servlet use Bean

    According to Sun's definition, JavaBean is a reusable software components. In fact JavaBean is a Java class, through the package into a property and methods of treatment of a function or a business object, referred to as bean. Because JavaBean is ...

  • Hibernate.cfg.xml configuration file (including the primary key generation strategy Introduction)

    Hibernate.cfg.xml configuration file: <? xml version = "1.0" encoding = "utf-8"?> <! DOCTYPE hibernate-configuration PUBLIC "- / / Hibernate / Hibernate Configuration DTD / / EN" "hibernate-configuration-2.0.dtd

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries