report Posts

Creating Web Based Reports using Jasper Report

It’s easy to export reports to PDF if you do it in desktop application, but what if you had to do it in a web-based application? Here im trying to demonstrate on how to use servlets to generate a pdf based reports, using JasperReport libraries of course.

First, as always, a simple postgresql table,
on database “test”, schema “test”.

DROP TABLE master;
CREATE
    TABLE test.master
    (
        nama CHARACTER VARYING(30) NOT NULL,
        usia SMALLINT,
        CONSTRAINT idnama PRIMARY KEY (nama)
    )

Next step is a very simple jrxml file, i named it reportTest.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reportTest" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<field name="nama" class="java.lang.String"/>
	<field name="usia" class="java.lang.Short"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="31" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="0" width="555" height="31"/>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font size="24" isBold="true"/>
				</textElement>
				<text><![CDATA[Test Report Page]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band height="11" splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="8" splitType="Stretch"/>
	</columnHeader>
	<detail>
		<band height="25" splitType="Stretch">
			<textField>
				<reportElement x="19" y="0" width="100" height="20"/>
				<textElement textAlignment="Center"/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{nama}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="168" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.Short"><![CDATA[$F{usia}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="20" splitType="Stretch">
			<textField pattern="dd MMMMM yyyy">
				<reportElement x="455" y="0" width="100" height="20"/>
				<textElement textAlignment="Right"/>
				<textFieldExpression class="java.util.Date"><![CDATA[new java.util.Date()]]></textFieldExpression>
			</textField>
		</band>
	</columnFooter>
	<pageFooter>
		<band splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="6" splitType="Stretch"/>
	</summary>
</jasperReport>

Im using Hibernate as my ORM library, thats why i need a java bean and a hbm.xml file,

package com.edw.report.bean;

public class Master  implements java.io.Serializable {

    private String nama;
    private Short usia;

    public Master() {
    }

    // other setters and getters

    @Override
    public String toString() {
        return "Master{" + "nama=" + nama + " usia=" + usia + '}';
    }
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.edw.report.bean.Master" table="master" schema="test">
        <id name="nama" type="string">
            <column name="nama" length="30" />
            <generator class="assigned" />
        </id>
        <property name="usia" type="java.lang.Short">
            <column name="usia" />
        </property>
    </class>
</hibernate-mapping>

And this is my main hibernate configuration file, hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/test</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">password</property>
    
    <mapping resource="com/edw/report/bean/Master.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

And a factory class to load my hibernate configuration file, it’s actually by default load hibernate.cfg.xml file.

package com.edw.report.util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author edw
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

And finally, my servlet class. It use Jasper Report libraries, and export my report to PDF by changing its header to application/pdf instead of text/html. Take a look at line 53, class FileInputStream load my reportTest.jasper file that located under WEB-INF folder.

package com.edw.report.servlet;

import com.edw.report.bean.Master;
import com.edw.report.util.HibernateUtil;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.data.JRBeanCollectionDataSource;

import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.log4j.Logger;
import org.hibernate.Session;

/**
 *
 * @author edw
 */
public class ReportServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(ReportServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // set header as pdf
        response.setContentType("application/pdf");

        // set input and output stream
        ServletOutputStream servletOutputStream = response.getOutputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fis;
        BufferedInputStream bufferedInputStream;

        try {
            // get report location
            ServletContext context = getServletContext();
            String reportLocation = context.getRealPath("WEB-INF");

            // get report
            fis = new FileInputStream(reportLocation + "/reportTest.jasper");
            bufferedInputStream = new BufferedInputStream(fis);

            // fetch data from database
            Session session = HibernateUtil.getSessionFactory().openSession();
            List<Master> masters = (List<Master>) session.createCriteria(Master.class).list();
            session.close();

            // log it
            for (Master master : masters) {
                logger.debug(master.toString());
            }

            // fill it
            JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(masters);
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), jrbcds);

            // export to pdf
            JasperExportManager.exportReportToPdfStream(jasperPrint, baos);

            response.setContentLength(baos.size());
            baos.writeTo(servletOutputStream);

            // close it
            fis.close();
            bufferedInputStream.close();

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            servletOutputStream.flush();
            servletOutputStream.close();
            baos.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Reporting Servlet";
    }
}

Dont forget to register your servlet to web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>ReportServlet</servlet-name>
        <servlet-class>com.edw.report.servlet.ReportServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ReportServlet</servlet-name>
        <url-pattern>/ReportServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Here is my Netbeans’ project screenshoot



Btw if you are using Struts 1, it will be easier. All you have to do is create an Action class to handle all the reporting, and register it to struts-config.xml. Here is my example.

package com.edw.action;

public class ReportAction extends org.apache.struts.action.Action {

    private static final String SUCCESS = "success";
    private Logger logger = Logger.getLogger(ReportAction.class);

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        ServletContext context = getServlet().getServletContext();
        String reportLocation = context.getRealPath("WEB-INF");

        List<Log> logs = logService.select();

        FileInputStream fis = new FileInputStream(reportLocation+"/report.jasper");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);

        ServletOutputStream servletOutputStream = response.getOutputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Map<String, String> map = new HashMap<String, String>();
        JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(logs);
        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);

        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, jrbcds);

        response.setContentType("application/pdf");
        JasperExportManager.exportReportToPdfStream(jasperPrint, baos);

        response.setContentLength(baos.size());
        baos.writeTo(servletOutputStream);

        // close all
        fis.close();
        bufferedInputStream.close();

        servletOutputStream.flush();
        servletOutputStream.close();

        return mapping.findForward(SUCCESS);
    }
}

dont forget to put your Action class on your struts-config.xml

<action path="/report" type="com.edw.action.ReportAction"/>

Hope this can help others, have fun. (*)

Google+

How to Handle Jasper Report’s CompilationFailedException

I always use JasperReport for my java projects, but sometimes i found some weird java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException when im trying to get reports from jasper files. This is my full stack trace exception.

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/codehaus/groovy/control/CompilationFailedException
        at java.lang.Class.getDeclaredConstructors0(Native Method)
        at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
        at java.lang.Class.getConstructor0(Class.java:2699)
        at java.lang.Class.newInstance0(Class.java:326)
        at java.lang.Class.newInstance(Class.java:308)
        at net.sf.jasperreports.engine.JasperCompileManager.getCompiler(JasperCompileManager.java:472)
        at net.sf.jasperreports.engine.JasperCompileManager.loadEvaluator(JasperCompileManager.java:238)
        at net.sf.jasperreports.engine.fill.JRFillDataset.createCalculator(JRFillDataset.java:416)
        at net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:408)
        at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:74)
        at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:56)
        at net.sf.jasperreports.engine.fill.JRFiller.createFiller(JRFiller.java:143)
        at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:79)
        at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:624)

Actually it happens because im still using Groovy as my report language, instead of Java. All i have to do is change reporting language to java, as you can see below.

Or adding groovy*.jar to your project’s classpath.

Have fun, cheers. (B)

Google+

Creating a Simple Reporting Application using JasperReport and iBatis Framework

In this article i’m trying to create a very simple reporting application. In my several past projects, i used to do reporting with java swing and jasper report, and im connecting both of them using a simple JDBC and java.sql.Connection. But in recent project, i had to used iBatis Framework for replacing JDBC. So i had to spend several hours finding a workaround on how connecting Jasper with iBatis, but thanks to uncle Google i finally found a very simple but elegant workaround.
Enough with the chit-chat, i’ll show you the code. First, as always, a simple database named “test” and a simple table named “contoh”.

CREATE DATABASE 'test'
USE 'test'

CREATE TABLE `contoh` (
  `nama` varchar(30) NOT NULL DEFAULT '',
  `alamat` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`nama`)
)

next step is creating a java bean for database mapping

package com.edw.bean;

public class Contoh {

    private String nama;
    private String alamat;

    public String getAlamat() {
        return alamat;
    }

    public void setAlamat(String alamat) {
        this.alamat = alamat;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }
    
}

and an xml mapping for database queries, i named it contoh.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" 
"http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="contoh" >

  <resultMap id="result" class="com.edw.bean.Contoh">
        <result property="nama" column="NAMA" columnIndex="1"/>
        <result property="alamat" column="ALAMAT" columnIndex="2"/>
    </resultMap>

    <insert id="insertContoh" parameterClass="com.edw.bean.Contoh" >
    insert into contoh (nama, alamat)
    values (#nama:VARCHAR#, #alamat:VARCHAR#)
    </insert>

    <select id="selectAllContoh" resultMap="result">
    select nama, alamat
    from contoh
    </select>

</sqlMap>

and ibatis’ main xml configuration, sqlmapconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <settings
        useStatementNamespaces="true"
        lazyLoadingEnabled="true"
        enhancementEnabled="true"
        maxSessions="20"
        />

    <transactionManager type="JDBC" commitRequired="false">
        <dataSource type="SIMPLE">

            <property name="SetAutoCommitAllowed" value="false"/>
            <property name="DefaultAutoCommit" value="false"/>
            
            <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
            <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/test"/>
            <property name="JDBC.Username" value="root"/>
            <property name="JDBC.Password" value="password"/>
   
        </dataSource>
    </transactionManager>

    <sqlMap resource="com/edw/sqlmap/contoh.xml"/>
</sqlMapConfig>

next step is creating a simple java class to load all iBatis’ configuration file.

package com.edw.config;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.IOException;
import java.io.Reader;


/**
 *
 * @author edw
 */
public class SqlMapConfig {

    protected static final SqlMapClient sqlMap;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/sqlmapconfig.xml");
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch (IOException e) {
            throw new RuntimeException("Fatal Error, ga dapet sqlmapconfignya.  Cause: " + e, e);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlMapClient getSqlMap() {
        return sqlMap;
    }
}

I create a very simple reporting using JasperReport, i named it Iseng.jrxml and compile it into Iseng.jasper

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Iseng" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.zoom" value="1.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<parameter name="nama1" class="java.lang.String"/>
	<queryString>
		<![CDATA[]]>
	</queryString>
	<field name="nama" class="java.lang.String"/>
	<field name="alamat" class="java.lang.String"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="56" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="0" width="555" height="46"/>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font size="24"/>
				</textElement>
				<text><![CDATA[Testing Report]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band height="13" splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="34" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="11" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<text><![CDATA[Nama]]></text>
			</staticText>
			<staticText>
				<reportElement x="225" y="11" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<text><![CDATA[Alamat]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="27" splitType="Stretch">
			<textField>
				<reportElement x="32" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{nama}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="225" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{alamat}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="45" splitType="Stretch"/>
	</columnFooter>
	<pageFooter>
		<band height="54" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="42" splitType="Stretch"/>
	</summary>
</jasperReport>

And this is my main Swing class. iBatis generate a List of Beans class for its result set, and im using Jasper’s JRBeanCollectionDataSource class to map iBatis’ resultSet.

package com.edw.ui;

import com.edw.bean.Contoh;
import com.edw.config.SqlMapConfig;
import com.ibatis.sqlmap.client.SqlMapClient;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.FileInputStream;

import java.util.HashMap;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;

import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class Main extends JFrame implements ActionListener {

    private Logger logger = Logger.getLogger(this.getClass());
    private JButton cmdPrint = new JButton("cetak");
    private SqlMapClient sqlMapClient = SqlMapConfig.getSqlMap();

    public Main() {
        Container conn = getContentPane();
        conn.setLayout(new FlowLayout());
        conn.add(cmdPrint);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cmdPrint.addActionListener(this);
        pack();
    }

     public void actionPerformed(ActionEvent e) {
        if (e.getSource() == cmdPrint) {
            try {
                //load report location
                FileInputStream fis = new FileInputStream("Iseng.jasper");
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);

                // do query and get list of Contoh
                List<Contoh> contohs = sqlMapClient.queryForList("contoh.selectAllContoh");

                //fill it in JRBeanCollectionDS
                JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(contohs);

                //compile report
                JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), jrbcds);

                //view report to UI
                JasperViewer.viewReport(jasperPrint, false);

            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }

        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.setVisible(true);
    }
}

and my log4j configuration, i named it log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG,stdout

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n

this is my NetBeans’ project structure,
Netbeans 6.9 project structure

dont forget to put your .jasper file in the same folder as your build.xml file,
Netbeans 6.9 file structure

this is what happen when i run my application, on the background you can see iBatis’ resultSet.
iBatis UI and its ResultSet

and this is what happen when i push my report button
JasperViewer showing iBatis' resultSet

I hope my article can be useful for others, thank you and have fun using iBatis.
(H)

Google+

Membuat Aplikasi Reporting sederhana dengan JasperReport dan Java Swing

Beberapa hari terakhir ini, gw ditanyain terus tentang caranya connect java swing ke jasper report. Dan konyolnya, gw juga udah lupa caranya. Maklum, kebanyakan copy-paste jadi begini niy. Ya udh supaya inget dan gag lupa-lupa lagi, gw paste disini aja sourcenya.

Gw coba bikin report gembel sederhana dulu, yg ambil data nama dan alamat dari table “contoh” yang ada di database “test”. Pertama-tama kita bikin dulu table nya didatabase,

CREATE TABLE `contoh` (
  `nama` varchar(30) NOT NULL DEFAULT '',
  `alamat` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`nama`)
)

Abis itu kita bikin file jrxml-nya, nanti file jrxml ini akan dicompile on-the-fly oleh compiler jadi .jasper.

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Iseng" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<parameter name="nama1" class="java.lang.String"/>
	<queryString>
		<![CDATA[SELECT
     contoh.`nama` AS contoh_nama,
     contoh.`alamat` AS contoh_alamat
FROM
     `contoh` contoh
where contoh.`nama` like $P{nama1}]]>
	</queryString>
	<field name="contoh_nama" class="java.lang.String">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<field name="contoh_alamat" class="java.lang.String">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="56" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="0" width="555" height="46"/>
				<textElement textAlignment="Center" verticalAlignment="Middle">
					<font size="24"/>
				</textElement>
				<text><![CDATA[Testing Report]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band height="13" splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="34" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="11" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<text><![CDATA[Nama]]></text>
			</staticText>
			<staticText>
				<reportElement x="132" y="11" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<text><![CDATA[Alamat]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="27" splitType="Stretch">
			<textField>
				<reportElement x="0" y="0" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{contoh_nama}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="132" y="0" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{contoh_alamat}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="45" splitType="Stretch"/>
	</columnFooter>
	<pageFooter>
		<band height="54" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="42" splitType="Stretch"/>
	</summary>
</jasperReport>

Di situ gw bikin satu report yang akan mencari data di table contoh berdasarkan query nama. Perhatikan line 10, itu adalah variabel yang akan gw gunakan untuk menjadi variabel query report.

Setelah jadi reportnya, sekarang gw lanjut bikin tampilannya. Gw pakek java Swing buat bikin UI. Jadi harap maklum klo rada kacrut sederhana.

package com.edw.frame;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;

import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class FrameMain extends JFrame implements ActionListener {

    private Logger logger = Logger.getLogger(FrameMain.class);
    private JTextField txtNama = new JTextField(20);
    private JButton cmdPrint = new JButton("cetak");

    public FrameMain() {
        init();
    }

    private void init() {
        Container conn = getContentPane();
        conn.setLayout(new FlowLayout());
        conn.add(new JLabel("Iseng"));
        conn.add(txtNama);
        conn.add(cmdPrint);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cmdPrint.addActionListener(this);
        pack();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == cmdPrint) {
            try {
                // parameter
                String parameterNama = txtNama.getText();

                //load report location
                FileInputStream fis = new FileInputStream("src\\com\\edw\\rpt\\Iseng.jrxml");
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);

                //set parameters
                Map<String, String> map = new HashMap<String, String>();
                map.put("nama1", parameterNama);

                Class.forName("com.mysql.jdbc.Driver");
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "xxxx");


                //compile report
                JasperReport jasperReport = (JasperReport) JasperCompileManager.compileReport(bufferedInputStream);
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, connection);

                //close connection
                connection.close();

                //view report to UI
                JasperViewer.viewReport(jasperPrint, false);

            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }

        }
    }

    public static void main(String[] args) {
        new FrameMain().setVisible(true);
    }
}

Coba cek di line 64, itu adalah parameter yang akan dikirim ke report, pastikan nama variabelnya sama dengan nama variabel yang ada di jasper report ( file jrxml ). Sedangkan line 67 adalah Koneksi database gw, silahkan di modifikasi sesuai keinginan.

Nanti klo udh dijalanin, jadinya kayak gini
Form UI

terus klo misalkan text field nya diisi dengan “edwin” dan kemudian menekan tombol “cetak”, maka akan muncul form report dengan data “edwin” yang kita cari.
report jasper

berikut adalah struktur project gw serta library (jar) apa aja yg gw pake.
jasper report jar project structure
harap diingat, lokasi jar yg gw pake ada di dalam folder instalasi Jasper Report, silahkan di search aja.

nah ini adalah isi database gw, coba di cek output dari jasper dan isi databasenya, sinkron apa engga.
isi db

Sekian dan terima kasih.

nb. Oh iya, hasil preview dari jasper report juga bisa di save as ke berbagai macam format, tinggal di save aja.
export jasper into another format

Google+