Javaweb + jasperreports report + struts2, javaweb report tool

Source: Internet
Author: User

Javaweb + jasperreports report + struts2, javaweb report tool
This article describes in detail the jasperreports report development method using the struts2 framework in Java Web. The data source selects connection. The template selects the compiled template (jasper format file ).

Many tutorials on the Internet using the jasperreports-3.x.x of the api, This article uses the jarjasperreports-5.6.0.jar of the api, the difference between the two versions is still very large, 3. x. x version of a lot of methods have been obsolete.

We recommend that you use a unified jarjasperreports-5.6.0.jar version, because these tools for generating reports are currently available, and the jar package is also complete. There are development tools for version 3.x. x, but the supporting jar packages can only be found one by one, and many other methods are outdated.

Jasperreports can have a variety of data sources, such as list, JavaBean, and connection. In order not to be associated with the background service layer and dao layer, we use connection as the data source. (If hibernate and other frameworks are used in the background, obtaining data sources such as list and JavaBean requires a lot of work: Writing JavaBean and writing ing files; if we use the connection data source, we can write the SQL statement in the template. In the action, we only need to pass the map format parameter and connection)

The required HttpServletResponse object and ServletContext object can be obtained through implementing the ServletResponseAware and ServletContextAware interfaces. For more methods, refer to this link.

Path processing in the jasperreports class is very tangled. To facilitate the process, the getRealPath method of servletContext is used in a unified manner.

Selecting the compiled template can reduce the server load. In addition, if you compile the template in action, it is easy to cause errors during compilation because the compiler version and the report generation tool version are inconsistent. Jdt-compiler-3.1.1.jar and jasperreports-5.6.0.jar are matched. In addition, jaspersoft and ireport can be easily compiled. (The following example code pdf method contains the compilation)

Download Links for relevant code, tools, reference documents, and source code


1. Using struts2, the result is not configured in the action. Of course, the corresponding method in the action does not need to return a value. The JRExporter object exportReport () is used to output the result to the browser.

1. Develop a report file in jrxml format, which can be developed using jaspersoft-studio or ireport. Put it in the WebRoot directory of our web project.

2. Compile a jrxml file into a jasper file.

3. Fill in data for files in jasper format and generate files or streams in jrprint format (other file formats cannot be generated, and files in jrprint format can be serialized ). For example, use JasperFillManager. fillReport to generate a jrprint file.

4. use the specific implementation classes HtmlExporter, jrw.exporter, and JRXlsExporter of the JRExporter interface to generate html, pdf, and xls files in jrprint format and export them to the OutputStream of response, output to the browser page. (Of course, JasperExportManager can also be used to replace the previous JRExporter implementation class. However, this class can only process files in the format of 3 (pdf, html, xml, to process other formats, use the specific JRExporter implementation class)

For the above process, refer to (picture comes from the Network)


JasperReports-related classes involved in the development process



2. Using struts2, the result is not configured in the action, and the corresponding method in the action has no return value. In the action, the OutputStream Class Object of the HttpServletResponse class is directly called for output to the browser side.

1. Develop a report file in jrxml format, which can be developed using jaspersoft-studio or ireport. Put it in the WebRoot directory of our web project.

2. Compile a jrxml file into a jasper file.

3. Fill the jasper file with data and output it to the OutputStream stream of response. You can use the JasperRunManager method. In addition, JasperRunManager can generate html, pdf, xsl, and other format files on the hard disk.

4. Use the setContentType method of HttpServletResponse to set the returned data type, and use the flush () method and close () method of the OutputStream class to output the data to the browser.


3. Use struts2 to configure the result in the action. Of course, the corresponding method must return a value. Select stream as the result type. You need to configure the response content format contentType and output it to the inputName of the browser (the value of this parameter is an InputStream stream, we can use new FileInputStream to generate input streams for the generated pdf, html, and xsl files.

1. Develop a report file in jrxml format, which can be developed using jaspersoft-studio or ireport. Put it in the WebRoot directory of our web project.

2. Compile a jrxml file into a jasper file.

3. Use JasperRunManager to generate (pdf, html, etc.) files in specific formats, and use new FileInputStream to generate InputStream stream objects. The rest are handed over to the struts2 configuration file.



The example code corresponding to the above three methods is as follows: (corresponding to the pdf1, pdf2, and pdf3 methods respectively. The pdf method includes compiling jrxml into jasper)

Struts. xml configuration

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>    <constant name="struts.devMode" value="true" />    <package name="test" extends="struts-default" namespace="/test">        <action name="pdf" class="test.TestAction" method="pdf">          </action>        <action name="pdf1" class="test.TestAction" method="pdf1">          </action>        <action name="pdf2" class="test.TestAction" method="pdf2">          </action>        <action name="pdf3" class="test.TestAction" method="pdf3">          <result name="success" type="stream">  <param name="contentType">application/pdf</param>  <param name="inputName">inputStream</param>  <param name="bufferSize">1024</param></result>        </action>    </package></struts>

Action Code

Package test; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. SQL. connection; import java. SQL. driverManager; import java. util. hashMap; import javax. servlet. servletContext; import javax. servlet. servletOutputStream; import javax. servlet. http. httpServletResponse; import net. sf. jasperreports. engine. jasperCompileManager; import net. sf. jasperreports. engine. jasperFillMana Ger; import net. sf. jasperreports. engine. jasperRunManager; import net. sf. jasperreports. engine. export. jrw.exporter; import net. sf. jasperreports. export. simpleExporterInput; import net. sf. jasperreports. export. simpleOutputStreamExporterOutput; import net. sf. jasperreports. export. simpletransferexporterconfiguration; import org. apache. struts2.interceptor. servletResponseAware; import org. apache. struts2.util. servletCo NtextAware; import com. opensymphony. xwork2.ActionSupport; public class TestAction extends ActionSupport implements ServletResponseAware, ServletContextAware {HttpServletResponse response; ServletContext servletContext; InputStream inputStream; public void pdf () {long start = System. currentTimeMillis (); try {// database connection Class. forName ("com. mysql. jdbc. driver "); Connection conn = DriverManager. getConnection ("jdbc: Mysql: // localhost/test? User = root & password = flf1989317 "); String reportSource = servletContext. getRealPath ("/jasper/jasper_template.jrxml"); System. out. println (reportSource); File parent = new File (reportSource ). getParentFile (); String reportDestination = new File (parent, "complied_jasper_template.jasper "). getAbsolutePath (); // uncompiled. reports in jrxml format are compiled and generated. jasperCompileManager. compileReportToFile (reportSource, reportDestina Tion); // obtain the output stream ServletOutputStream servletOutputStream = response. getOutputStream (); // obtain the input stream InputStream inputStream = new FileInputStream (reportDestination) of the jasper report file; // generate the Map object HashMap hm = new HashMap (); hm. put ("test", new Integer (20); // generate the output stream JasperRunManager in pdf document format. runReportToPdfStream (inputStream, servletOutputStream, hm, conn); response. setContentType ("application/pdf"); servletOutputStream. flush (); ServletOutputStream. close ();} catch (Exception e) {e. printStackTrace ();} System. err. println ("Filling time:" + (System. currentTimeMillis ()-start);} public void pdf1 () {long start = System. currentTimeMillis (); try {// generate the Map object HashMap hm = new HashMap (); hm. put ("test", new Integer (20); // database connection Class. forName ("com. mysql. jdbc. driver "); Connection conn = DriverManager. getConnection ("jdbc: mysql: // l Ocalhost/test? User = root & password = flf1989317 "); String jasperFile = servletContext. getRealPath ("/jasper/complied_jasper_template.jasper"); // JasperPrint perprint = JasperFillManager. fillReport (jasperFile, hm, conn); String jrprintPath = servletContext. getRealPath ("/jasper/template. jrprint "); // File jrprintFile = new File (jrprintPath); JasperFillManager. fillReportToFile (jasperFile, jrprintPath, hm, conn); jr1_export Er exporter = new jr1_exporter (); // exporter. setExporterInput (new SimpleExporterInput (jasperPrint); exporter. setExporterInput (new SimpleExporterInput (jrprintPath); // String pdfFilePath = servletContext. getRealPath ("/jasper/template.pdf"); // output to hard disk // exporter. setExporterOutput (new SimpleOutputStreamExporterOutput (pdfFilePath); // output to the response stream, which is displayed in the browser exporter. setExporterOutput (new SimpleOutputStreamExporterO Utput (response. getOutputStream (); simpledeskexporterconfiguration configuration = new simpledeskexporterconfiguration (); // you can use the configuration object to set various attributes of the output pdf document. // configuration. setCreatingBatchModeBookmarks (true); exporter. setConfiguration (configuration); exporter. exportReport ();} catch (Exception e) {e. printStackTrace ();} System. err. println ("Filling time:" + (System. currentTimeMillis ()-start);} pub Lic void pdf2 () {long start = System. currentTimeMillis (); try {// database connection Class. forName ("com. mysql. jdbc. driver "); Connection conn = DriverManager. getConnection ("jdbc: mysql: // localhost/test? User = root & password = flf1989317 "); String reportDestination = servletContext. getRealPath ("/jasper/complied_jasper_template.jasper"); ServletOutputStream servletOutputStream = response. getOutputStream (); // obtain the input stream InputStream inputStream = new FileInputStream (reportDestination) of the jasper report file; // generate the Map object HashMap hm = new HashMap (); hm. put ("test", new Integer (20); // generate the output stream JasperRunManager in pdf document format. runreporttosponst Ream (inputStream, servletOutputStream, hm, conn); response. setContentType ("application/pdf"); servletOutputStream. flush (); servletOutputStream. close ();} catch (Exception e) {e. printStackTrace ();} System. err. println ("Filling time:" + (System. currentTimeMillis ()-start);} public String pdf3 () {long start = System. currentTimeMillis (); try {// database connection Class. forName ("com. mysql. jdbc. driver "); Connection conn = DriverManager. getConnection ("jdbc: mysql: // localhost/test? User = root & password = flf1989317 "); String reportDestination = servletContext. getRealPath ("/jasper/complied_jasper_template.jasper"); String pdfFilePath = servletContext. getRealPath ("/jasper/template.pdf"); HashMap hm = new HashMap (); hm. put ("test", new Integer (20); JasperRunManager. runReportToPdfFile (reportDestination, pdfFilePath, hm, conn); inputStream = new FileInputStream (pdfFilePath);} catch (Exception e) {e. printStackTrace ();} System. err. println ("Filling time:" + (System. currentTimeMillis ()-start); return SUCCESS;} public void setServletResponse (HttpServletResponse response) {// TODO Auto-generated method stubthis. response = response;} public void setServletContext (ServletContext servletContext) {// TODO Auto-generated method stubthis. servletContext = servletContext;} public InputStream getInputStream () {return inputStream ;}}



4. Use the jasperreports plug-in of struts2 to output reports to the browser. This plug-in requires a file in the jasper format, which is filled with the data source dateSource of the file in the jasper format (refer to the api generation of jasperReports), and the output type format (HTML, PDF, etc ).

Because the struts2-jasperreports-plugin-2.3.14.jar plug-in corresponds to the jasperreports-3.1.2.jar version, if you use a higher version of jasperreports or ireport tool to generate a file in the jasper format, here there will be some conflict. The sample code related to this method is not provided.

The configuration of struts. xml can be referred to as follows:

<package name="default"extends="jasperreports-default"><action name="PDF" class="XXX">            <result name="success" type="jasper">                <param name="location">                    /jasper/template.jasper                </param>                <param name="dataSource">YYY</param>                <param name="format">PDF</param>            </result>        </action></package>




What packages are required to generate a report using JasperReports in Struts2?

Struts2-jasperreports-plugin-2.0.14.jar, jasperreports-3.5.2.jar, commons-collections-3.1.jar, commons-beanutils-1.8.0.jar, jdt-compiler-3.1.1.jar,
IText-2.1.0.jar

Jasperreports + struts2 report generation Error

No such parameter REPORT_CONTEXT

Parameter missing
 

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.