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 and a class. 
 package util; 
 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); } 
 package util;
 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.export.JRXlsExporter; 
 public class ReportGenerator{ 
 @SuppressWarnings({"unchecked" })
 public static void generate(HttpServletRequest request, HttpServletResponse response, Collection data)
 String format = request.getParameter("FORMAT");
 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();
 String reportList = (String)request.getAttribute("REPORT");
 response.getOutputStream().write(generate(format,reportList, params, data));
 } 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;
 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);
 { 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);
 JasperExportManager.exportReportToPdfStream(jasperPrint, bos);
 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 and in pojo package 
 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)
 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;
 package pojo; 
 public class Phone { 
 private String phoneType;
 private String phoneNumber;
 public Phone(String phoneType, String phoneNumber)
 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" "">
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <title>Sample Jasper Report</title>
 <a href="myServlet">Download Report</a>
 </body> </html>
 Now deploy the war in tomcat.


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:
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…

lucene example

In simple words: it parses a text and without saving the text the framework can search inside it. It keeps track of terms used inside the text. Of course you can optionally save the text into your <a href="" data-cke-saved-href="">lucene index</a>.

 Lets take an example.

 I have created a database and a table named it 'city'.

 create table `city` (

 `id` bigint (20),

 `city_name` varchar (765)


 Now I have added two record Kolkata,Delhi in the database.

 Now create a java project and add lucene-analyzers-common-4.0.0.jar,lucene-core-4.0.0.jar,lucene-queries-4.0.0.jar,lucene-queryparser-4.0.0.jar and mysql-connector-java-5.1.22-bin.jar in the project.

 create a java class named LuceneTest  and write the following.

LuceneTest .java

 package com.test;

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