Skip to main content

sample jasper report

Sample Jasper Report 
Tools:   Java jdk 1.5 or above Eclipse
commons-beanutils-1.7.0.jar ,commons-collections-3.2.1.jar ,commons-digester-1.7.jar, commons-io-1.4.jar, iText-2.1.7.jar,
jasperreports-4.5.0.jar,jfreechart-1.0.12.jar, log4j.jar servlet-api.jar 
Create a Dynamic Web Project in eclipse and add a servlet name MyServlet.java and a ReportGenerator.java class. 
 MyServlet.java 
 package util; 
 import java.io.IOException;
 import java.util.ArrayList;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import pojo.Person; import pojo.Phone;
 public class MyServlet  extends HttpServlet{ 
 private void process(HttpServletRequest request, HttpServletResponse response){ 
 ArrayList<Person> persons = new ArrayList<Person>();
 ArrayList<Phone> phones = null; 
 phones = new ArrayList<Phone>();
 phones.add(new Phone("Mobile 1","94000001"));
 phones.add(new Phone("Mobile 2","94000002"));
 persons.add(new Person("admin","admin", phones));
 phones = new ArrayList<Phone>();
 phones.add(new Phone("Mobile 1","94000003"));
 phones.add(new Phone("Mobile 2","94000004"));
 persons.add(new Person("test","test", phones)); 
 request.setAttribute("REPORT", "reportBean.jrxml,reportBean_subreport.jrxml");
 ReportGenerator.generate(request, response, persons); } 
 @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 process(request, response);
 }
 @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 { process(request, response); } 
 } 
 ReportGenerator.java 
 package util;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.net.URISyntaxException;
 import java.util.Collection;
 import java.util.Enumeration;
 import java.util.HashMap;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 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.data.JRBeanCollectionDataSource;
 import net.sf.jasperreports.engine.export.JRXlsExporter; 
 public class ReportGenerator{ 
 @SuppressWarnings({"unchecked" })
 public static void generate(HttpServletRequest request, HttpServletResponse response, Collection data)
 { 
 try{
 response.setContentType("application/octet-stream");
 String format = request.getParameter("FORMAT");
 if(format==null)format="pdf";
 response.setHeader("Content-Disposition", "attachment; filename=\"report_"+ new java.util.Date().getTime() +"."+format+"\"");
 HashMap params = new HashMap();
 Enumeration e = request.getAttributeNames();
 while(e.hasMoreElements()) {
 String key = (String)e.nextElement();
 params.put(key,request.getAttribute(key));
 }
 String reportList = (String)request.getAttribute("REPORT");
 response.getOutputStream().write(generate(format,reportList, params, data));
 response.flushBuffer();
 } catch(Exception e)
 { e.printStackTrace(); }   }
 @SuppressWarnings({ "unchecked" })
 public static byte[] generate(String format, String reportList, HashMap params, Collection data) throws Exception
 { 
 System.out.println("Reports: "+reportList);
 System.out.println("Format: "+format);
 String rep_path = null;
 try
 {
 rep_path = ReportGenerator.class.getResource("/reports/").toURI().getPath();
 params.put("SUBREPORT_DIR", rep_path); }
 catch (URISyntaxException e)
 { e.printStackTrace(); } 
 JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(data);
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 String[] repList = reportList.split("[,]");
 for(int i=0;i<repList.length;i++)
 {   
 String rep = rep_path+repList[i];
 String rec = rep.replaceAll("jrxml","jasper");
 File file = new File(rec);
 if(!file.exists())
 {
 net.sf.jasperreports.engine.design.JasperDesign jasperDesign = net.sf.jasperreports.engine.xml.JRXmlLoader.load(rep);
 JasperCompileManager.compileReportToFile(jasperDesign,rec); }
 }
 JasperPrint jasperPrint = JasperFillManager.fillReport(rep_path+repList[0].replaceAll("jrxml","jasper"), params, dataSource);
 if(format.equals("pdf"))
 {
 JasperExportManager.exportReportToPdfStream(jasperPrint, bos);
 }
 if(format.equals("xls"))
 {
 JRXlsExporter exporter = new JRXlsExporter();
 exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, bos);
 exporter.exportReport(); }
 byte[] bytes = bos.toByteArray(); bos.close(); return bytes;
 }   
 }
 Add two pojo class Person.java and Phone.java in pojo package   
 Person.java 
 package pojo; 
 import java.util.ArrayList;
 public class Person {
 private String firstName;
 private String lastName;
 private ArrayList<Phone> phones = new ArrayList<Phone>();
 public Person(String firstName, String lastName, ArrayList<Phone> phones)
 {
 super();
 this.firstName = firstName;
 this.lastName = lastName;
 this.phones = phones;
 } 
 public String getFirstName() {
 return firstName;
 }
 public void setFirstName(String firstName)
 { this.firstName = firstName;
 }
 public String getLastName()
 { return lastName;
 }
 public void setLastName(String lastName)
 { this.lastName = lastName;
 }
 public ArrayList<Phone> getPhones()
 { return phones;
 }
 public void setPhones(ArrayList<Phone> phones)
 {
 this.phones = phones;
 } 
 } 
 Phone.java
 package pojo; 
 public class Phone { 
 private String phoneType;
 private String phoneNumber;
 public Phone(String phoneType, String phoneNumber)
 {
 super();
 this.phoneType = phoneType;
 this.phoneNumber = phoneNumber;
 }
 public String getPhoneType()
 {
 return phoneType;
 }
 public void setPhoneType(String phoneType)
 { this.phoneType = phoneType; }
 public String getPhoneNumber()
 { return phoneNumber; }
 public void setPhoneNumber(String phoneNumber)
 { this.phoneNumber = phoneNumber; }   
 } 
 Now Add Two report file 
 reportBean.jrxml and reportBean_subreport.jrxml in report package.
 Add index.jsp Index.jsp
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <title>Sample Jasper Report</title>
 </head>
 <body>
 <a href="myServlet">Download Report</a>
 </body> </html>
 Now deploy the war in tomcat.

Comments

Popular posts from this blog

jdbc mysql example in java

Here’s an example to show you how to connect to MySQL database via a JDBC driver.To connect to MySQL from Java, you have to use the JDBC driver from MySQL. You find the latest MySQL JDBC driver under the following URL:http://dev.mysql.com/downloads/connector/j.
Create a example database and named it test.Now create a a table name it user. Create table user ((userid INT NOT NULL AUTO_INCREMENT,
username VARCHAR(30) NOT NULL, PRIMARY KEY (userid)); Now add the record in your table; Now create a project in eclipse and mysql-connector jar in its classpath.package com.test;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; publicclass JavaJDBCExample { private Connection connect = null; private Statement statement = null; private ResultSet resultSet = null; publicvoid readDatabase() { try { // this will load the MySQL driver Class.forName("com.mysql.jdbc.Driver"); // setup the connection wi…

singleton design pattern

Java Singleton design pattern is one of the design pattern which suggest that only one instance of a Singleton object is created by the JVM. This is useful when exactly one object is needed to coordinate actions across the system Example: public class Singleton{ privatestatic Singleton singleton = null; private Singleton(){ } publicstaticsynchronized Singleton getInstance( ) { if(singleton == null) { singleton = new Singleton(); } returnsingleton; } publicvoid test( ) { System.out.println("test"); } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub returnnew CloneNotSupportedException(); } } publicclass SingletonTest { publicstaticvoid main(String[] args){ Singleton singleton = Singleton.getInstance(); try{ Singleton

Tomcat configuration

1. How to deploy web application in tomcat 
 Create a war file and deploy it in tomcat->webapps folder.Restart tomcat and write localhost:8080/YOURWEBAPPNAME. 
 2. Add jndi in tomcat 
 <Context>
 <Resource name="jdbc/myDB" auth="Container"
 type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000"
 username="admin" password="admin"
 driverClassName="com.mysql.jdbc.Driver"
 url="jdbc:mysql://localhost:3306/javatest"/> 
 </Context>
 in web.xml 
 <resource-ref>
 <description>DB Connection</description>
 <res-ref-name>jdbc/myDB</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
 </resource-ref> 
 3. Add user with manager role in tomcat   Tomcat-users.xml 
 <tomcat-users>
 <role rolename="manager"/>
 <user username="admin"…