Вы находитесь на странице: 1из 5

JSF + JPA + JasperReports (iReport) Part 1 | Ramki Java Blog

http://www.ramkitech.com/2011/11/jsf-jpa-jasperreports-ireport.html

Hi in this post we will see the overview of JasperReports and how to integrate into JSF application. JasperReports is the world's most popular open source reporting engine. It is entirely written in Java and it is able to use data coming from any kind of data source and produce pixelperfect documents that can be viewed, printed or exported in a variety of document formats including HTML, PDF, Excel, OpenOffice and Word. In Primeface library also use this JasperReports to generate the PDF, CSV and DOC formats with single line of code. see here. but its not flexible and we cant change template. so here we see the how to use JasperReports for create the template and integrate JSF 2.0. We are using iReport tool for crating template. Download JasperReports and iReport

Jasper Reports download from here. This zip contain jasper library and its dependencies and lots sample codes. iReport download from here Now create the simple JSF Application to retrieve the data from database using JPA, then create the template using iReport and then integrate into JSF application. JSF+JPA Java Persistence API is standard way to access the all ORM (Object Relational Mapping) tools like Hibernate, EclipseLink, TopLink,.. . These tools are internally use JDBC to access the database. the Heart of JPA is consist of two parts

persistence.xml - Its xml file describe the persistence provider (ORM provider) and connection information like database URL, username and password. or data source. Entity Classes - Its normal POJO class for each table in underlying table. This class is annotated with @Entity and some annotation provided by JPA. Its way to express and map the property in the class into table in the DB. These entity class are manually we can create or using IDE tools like Net beans IDE provide "Entity Classes From Database" option to auto generate the Entity Classes. (See video in below) Once these entity classes are created then we need to create CRUD methods to wrapping these entities for ease of use. These kind of classes also auto generate from "Session Beans from Entity Classes" option. Here we using GlassFish Server 3. Its supports EJB 3.1. Now we create the JSF page to display the entity classes in table structure and provide buttons for export into variety of formats.

index.xhtml
view plain print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28.

<h:head> <title>Facelet Title</title> </h:head> <h:body> <h:form> <h:commandbutton actionlistener="#{demoBean.PDF}" value="PDF"> <h:commandbutton actionlistener="#{demoBean.DOCX}" value="Docx"> <h:commandbutton actionlistener="#{demoBean.XLSX}" value="Xlsx"> <h:commandbutton actionlistener="#{demoBean.ODT}" value="Odt"> <h:commandbutton actionlistener="#{demoBean.PPT}" value="Ppt"> </h:commandbutton></h:commandbutton></h:commandbutton></h:commandbutton></h:commandbutton></h:form> <h:datatable border="1" value="#{demoBean.listOfUser}" var="user"> <h:column> <f:facet name="header"> User Name </f:facet> #{user.userId} </h:column> <h:column> <f:facet name="header"> Password </f:facet> #{user.password} </h:column> </h:datatable> </h:body>

1 de 5

Jasper Reports

06/03/2013 03:03 a.m.

JSF + JPA + JasperReports (iReport) Part 1 | Ramki Java Blog

http://www.ramkitech.com/2011/11/jsf-jpa-jasperreports-ireport.html

28.

</h:body>

Jasper Reports Once sample JSF application is completed then we going to integrate Jasper Reports. First, include all necessary lib into our application. We already download the jasper library zip file. Extract this file they have lots of folder. one for dist folder contain main jasperreports-4.1.3.jar file and lib folder contain all necessary dependencies. see the requirements of jasper reports from here. This is flow diagram of JasperReports.

Jasper Report Flow

Here we use iReport tool to generate the JRXML template. this file is pure xml file to describe the layout and place-holders. then we need to compile into jasper file. its binary format. this compilation process we can do in 2 ways. 1. Using iReport to compile the jrxml file into jasper 2. Using JasperReport API we can do through programme. This is the code snippet compile the jrxml file into jasper file
view plain print ?

01.

JasperCompileManager.compileReportToFile("report.jrxml", "report.jasper");

or we can use iReport to compile

2 de 5

06/03/2013 03:03 a.m.

JSF + JPA + JasperReports (iReport) Part 1 | Ramki Java Blog

http://www.ramkitech.com/2011/11/jsf-jpa-jasperreports-ireport.html

now compilation is finished. data is also ready. here data is java beans (entity beans) . This entity beans can't use directly. we wrap into one more class JRBeanCollectionDataSource then using JasperFillManager we generate JRPRINT object. code:
view plain print ?

01. 02.

JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(listOfUser); JasperPrint jasperPrint=JasperFillManager.fillReport("report.jasper", new HashMap(),beanCollectionDataSource);

once JasperPrint is ready then we export using JasperExportManager


view plain print ?

01.

JasperExportManager.exportReportToPdfFile(jasperPrint, "report.pdf");

For exporting into docx, xlsx, odt, ods, pptx formats we should use JRDocxExporter, JRXlsxExporter, JROdtExporter, JROdsExporter, JRPptxExporter and one more thing we don't want to store the exported format into file system. we need to send these formats to client via stream. Code:
view plain print ?

01. 02. 03. 04. 05. 06. 07. 08.

HttpServletResponse httpServletResponse= (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.docx"); ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream(); JRDocxExporter docxExporter=new JRDocxExporter(); docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream); docxExporter.exportReport(); FacesContext.getCurrentInstance().responseComplete();

here we get the OutputStream via FacesContext.

You can download this complete example from GitHub (or) Google Code DemoBean.xml
view plain print ?

3 de 5

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49.

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ramki.jsf; import import import import import import import import import import import import import import import import import import import import import import import java.io.IOException; java.util.HashMap; java.util.List; javax.ejb.EJB; javax.faces.bean.ManagedBean; javax.faces.bean.SessionScoped; javax.faces.context.FacesContext; javax.faces.event.ActionEvent; javax.servlet.ServletOutputStream; javax.servlet.http.HttpServletResponse; net.sf.jasperreports.engine.JRException; net.sf.jasperreports.engine.JRExporterParameter; net.sf.jasperreports.engine.JasperExportManager; net.sf.jasperreports.engine.JasperFillManager; net.sf.jasperreports.engine.JasperPrint; net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; net.sf.jasperreports.engine.export.oasis.JROdtExporter; net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; net.sf.jasperreports.engine.export.ooxml.JRDocxExporterParameter; net.sf.jasperreports.engine.export.ooxml.JRPptxExporter; net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter; org.ramki.entity.User; org.ramki.session.UserFacade;

/** * * @author ramki */ @ManagedBean @SessionScoped public class DemoBean { private List<user> listOfUser; @EJB UserFacade userFacade; public List<user> getListOfUser() { listOfUser=userFacade.findAll(); return listOfUser; } public void setListOfUser(List<user> listOfUser) { this.listOfUser = listOfUser; }

06/03/2013 03:03 a.m.

JSF + JPA + JasperReports (iReport) Part 1 | Ramki Java Blog


44. 45. 46. 47. 48. 49. 50. 51. 52. 53. return listOfUser; }

http://www.ramkitech.com/2011/11/jsf-jpa-jasperreports-ireport.html

54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113.

public void setListOfUser(List<user> listOfUser) { this.listOfUser = listOfUser; } JasperPrint jasperPrint; public void init() throws JRException{ JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(listOfUser); String reportPath= FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports /report.jasper"); jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),beanCollectionData Source); } public void PDF(ActionEvent actionEvent) throws JRException, IOException{ init(); HttpServletResponse httpServletResponse= (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf"); ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream(); JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream); FacesContext.getCurrentInstance().responseComplete();

} public void DOCX(ActionEvent actionEvent) throws JRException, IOException{ init(); HttpServletResponse httpServletResponse= (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.docx"); ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream(); JRDocxExporter docxExporter=new JRDocxExporter(); docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream); docxExporter.exportReport(); FacesContext.getCurrentInstance().responseComplete(); } public void XLSX(ActionEvent actionEvent) throws JRException, IOException{ init(); HttpServletResponse httpServletResponse= (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.xlsx"); ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream(); JRXlsxExporter docxExporter=new JRXlsxExporter(); docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream); docxExporter.exportReport(); FacesContext.getCurrentInstance().responseComplete(); } public void ODT(ActionEvent actionEvent) throws JRException, IOException{ init(); HttpServletResponse httpServletResponse= (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.odt"); ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream(); JROdtExporter docxExporter=new JROdtExporter(); docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream); docxExporter.exportReport(); FacesContext.getCurrentInstance().responseComplete(); } public void PPT(ActionEvent actionEvent) throws JRException, IOException{ init(); HttpServletResponse httpServletResponse= (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pptx"); ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream(); JRPptxExporter docxExporter=new JRPptxExporter(); docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, servletOutputStream); docxExporter.exportReport(); FacesContext.getCurrentInstance().responseComplete(); } } </user></user></user>

Update (02/01/2012): mourad mourad mentioned that reports absolute path is hardcoded like C:\\UsersramkiDesktopreport.jasper". This doesn't work once you deploy your application in another application server. Yes that's correct. now i fix it.. i used for simplicity purpose. I try to used getResourceAsStream() method. But it wont work. the reason is our report needs some supporting files like images. If ur report contain no image then u can use getResourceAsStream() method. So here i want the path of the report jasper file. Then this report engine get the images from that path.

view plain

print

01. 02.

String reportPath= FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports /report.jasper"); jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),beanCollectionDataSource);

4 de 5

Update (22/02/2012): DrAhmedJava commented that i noticed that you have an exception - getOutputStream() has already been called for this response- in your output, and it also happened to me. and i want to share the solution: (Thanks for sharing solution, i updated the code) The idea is that after the pdf() method writes the pdf to http response, the jsf servlet itself tries to reopen the response to write the html rendered from rendering stage of the life cycle, so the solution is to tell the jsf servlet that the response is complete and to skip

06/03/2013 03:03 a.m.

JSF + JPA + JasperReports (iReport) Part 1 | Ramki Java Blog

http://www.ramkitech.com/2011/11/jsf-jpa-jasperreports-ireport.html

The idea is that after the pdf() method writes the pdf to http response, the jsf servlet itself tries to reopen the response to write the html rendered from rendering stage of the life cycle, so the solution is to tell the jsf servlet that the response is complete and to skip the rest of life cycle:
view plain print ?

01. 02.

JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream); FacesContext.getCurrentInstance().responseComplete();

Update : For sub reports and Date Objects check Part 2 of this Series

5 de 5

06/03/2013 03:03 a.m.

Вам также может понравиться