[Tutorial] Belajar ZKoss Yuu…

Karena kebutuhan project yang mengharuskan gw bikin aplikasi RIA yang jalan diatas browser, gw terpaksa cari-cari framework AJAX yang cepet jadinya dan bagus tampilannya. ZKoss adalah pilihan pertama gw, kebetulan background gw Java jadinya ga terlalu sulit codingin si ZKoss ini.

Disini gw akan coba bikin aplikasi CRUD sederhana banget, antara ZKoss sebagai UI-nya, MySQL sebagai databasenya dan Hibernate buat menghubungkan keduanya. IDE yg gw pakek adalah Netbeans dan Webserver gw Apache Tomcat.

Kita mulai dengan struktur database gw,
nama database “test”, nama table “person”.

CREATE TABLE person
(
        name VARCHAR(20) NOT NULL,
        gender VARCHAR(10),
        birthdate DATE,
        age INT,
        PRIMARY KEY (name)
)

insert into person (name, gender, birthdate, age) values ('Christian Gonzales', 'Male', '1988-12-24', 29);
insert into person (name, gender, birthdate, age) values ('Firman Utina', 'Male', '1977-11-20', 28);
insert into person (name, gender, birthdate, age) values ('Irfan Bachdim', 'Male', '1990-01-01', 19);
insert into person (name, gender, birthdate, age) values ('Julia Perez', 'Female', '1966-04-18', 64);

Kemudian javabean dan hibernate xml-nya.

package com.baculsoft.zk.bean;

import java.util.Date;

public class Person {
    
    private String name;
    private int age;
    private String gender;
    private Date birthdate;

    public Person(String name, int age, String gender, Date birthdate) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.birthdate = birthdate;
    }

    public Person() {
    }    

    // other setter getter

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class catalog="test" name="com.baculsoft.zk.bean.Person" table="person">
    <id name="name" type="string">
      <column length="20" name="name"/>
      <generator class="assigned"/>
    </id>
    <property name="gender" type="string">
      <column length="10" name="gender"/>
    </property>
    <property name="birthdate" type="date">
      <column length="10" name="birthdate"/>
    </property>
    <property name="age" type="java.lang.Integer">
      <column name="age"/>
    </property>
  </class>
</hibernate-mapping>

Jangan sampe lupa settingan hibernate.cfg.xml-nya yeh.

<?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.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.autocommit">true</property>
    <property name="hibernate.show_sql">true</property>
    <mapping resource="com/baculsoft/zk/bean/Person.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

abis itu gw bikin class PersonDAO buat handle transaksi ke db

package com.baculsoft.zk.dao;

import com.baculsoft.zk.bean.Person;
import java.util.List;
import org.hibernate.Session;

// disini pake hibernate util bawaan zkoss
import org.zkoss.zkplus.hibernate.HibernateUtil;

public class PersonDAO {

    public List<Person> findAll() throws Exception {
        Session session = HibernateUtil.getSessionFactory().openSession();
        return (List<Person>) session.createCriteria(Person.class).list();
    }

    public boolean delete(Person person) throws Exception {
        if (person == null) {
            throw new Exception("empty person");
        }
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.delete(person);
        session.flush();
        session.close();
        return true;
    }

    public boolean insert(Person person) throws Exception {
        if (person == null) {
            throw new Exception("empty person");
        }
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.save(person);
        session.flush();
        session.close();
        return true;
    }

    public boolean update(Person person) throws Exception {
        if (person == null) {
            throw new Exception("empty person");
        }
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.update(person);
        session.flush();
        session.close();
        return true;
    }
}

nah, ini class Service adalah salah satu class yang paling diperlukan, coba cek baris ke 34, 43 dan 51. Itu method2 jadi semacem “listener” buat “event” yang terjadi di aplikasi.

package com.baculsoft.zk.service;

import com.baculsoft.zk.bean.Person;
import com.baculsoft.zk.dao.PersonDAO;
import java.util.List;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.util.GenericForwardComposer;

public class PersonService extends GenericForwardComposer {

    private PersonDAO dao = new PersonDAO();
    private Person person = new Person();
    
    private Logger logger = Logger.getLogger(PersonService.class);

    public Person getCurrent() {
        return person;
    }

    public void setCurrent(Person person) {
        this.person = person;
    }

    public List<Person> getAllPersons() {
        try {
            return dao.findAll();
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return null;
        }

    }

    public void onClick$add() {
        try {
            Person nowPerson = new Person(person.getName(), person.getAge(), person.getGender(), person.getBirthdate());
            dao.insert(nowPerson);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    public void onClick$update() {
        try {
            dao.update(person);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    public void onClick$delete() {
        try {
            dao.delete(person);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}

berikut ini adalah yang terpenting dari si aplikasi zkoss, yaitu UI-nya. Gw kasih nama “index.zul” (extension .zul bisa diganti sesuka loe di dalem web.xml). Perhatikan baris ke 34, 35 dan 36. Id-nya button harus sama dengan nama method di class PersonService. Dibaris ke 3 adalah class yang didaftarkan sebagai listener.

<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit"?>
<window id="win" width="900px" title="Person" border="normal" 
    apply="com.baculsoft.zk.service.PersonService">
    <listbox id="box" multiple="true" rows="5"
        model="@{win$composer.allPersons, load-after='add.onClick, delete.onClick, update.onClick'}"
        selectedItem="@{win$composer.current}">

        <listhead>
            <listheader label="Name" sort="auto(name)"/>
            <listheader label="Age" width="80px" sort="auto(age)" />
            <listheader label="Gender" width="170px" sort="auto(gender)" />
            <listheader label="Birthdate" width="170px" sort="auto(birthdate)" />
        </listhead>

        <listitem self="@{each='person'}" value="@{person}">
            <listcell label="@{person.name}"/>
            <listcell label="@{person.age}"/>
            <listcell label="@{person.gender}"/>
            <listcell label="@{person.birthdate}"/>
        </listitem>

    </listbox>

    <groupbox>
        <caption label="Person" />
        Name: <textbox id="name" cols="25" value="@{win$composer.current.name}" />
        Age: <intbox id="age" cols="1" value="@{win$composer.current.age}" />
        Gender: <combobox id="gender" value="@{win$composer.current.gender}">
                    <comboitem label="Male" description="Alpha Male"/>
                    <comboitem label="Female" description="Girl Power"/>
                    <comboitem label="Others" description="WTF..?!?!"/>
                </combobox>
        Birthdate: <datebox id="birthdate" cols="8" value="@{win$composer.current.birthdate}" />
        <button id="add" label="Add" height="24px"/>
        <button id="update" label="Update" height="24px"/>
        <button id="delete" label="Delete" height="24px"/>
    </groupbox>
</window>

last but not least, komponen terpenting dari aplikasi gw, yaitu web.xml.

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <description><![CDATA[Edw's ZK Application]]></description>
    <display-name>ZKossTest</display-name>

    <listener>
        <description>ZK listener for session cleanup</description>
        <listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
    </listener>
    <servlet>
        <description>ZK loader for ZUML pages</description>
        <servlet-name>zkLoader</servlet-name>
        <servlet-class>org.zkoss.zk.ui.http.DHtmlLayoutServlet</servlet-class>

        <init-param>
            <param-name>update-uri</param-name>
            <param-value>/zkau</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>zkLoader</servlet-name>
        <url-pattern>*.zul</url-pattern>
    </servlet-mapping>

    <servlet>
        <description>The asynchronous update engine for ZK</description>
        <servlet-name>auEngine</servlet-name>
        <servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>auEngine</servlet-name>
        <url-pattern>/zkau/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.zul</welcome-file>
    </welcome-file-list>
</web-app>

nanti kalo berhasil dijalankan akan tampil seperti ini di browser,

Berikut adalah struktur project netbeans gw, btw untuk library ZKoss dan Hibernate bisa di download dari web masing-masing.


Btw, contoh project gw bisa di download disini. Ternyata ZKoss ngga terlalu susah kan? (*)

Google+

19 Comments

odeng

about 5 years ago

salam kenal mas Bro, mantap banget tutorialnya nich, saya belajar baru belajar zk. masih baca2 dokumentasinya zk. sudah saya coba di atas, kok sepertinya gampang yach untuk melakukan CRUD. saya bandingkan dengan ada yang di dokumentasinya gampang ini ternyata. tapi saya masih bertanya2, kalo di dokumentasinya untuk membuat listener dan Event kita harus membuat misal keyword pada sebuah variabel dan method: @Wired @Listen tapi tutorial di atas kok ndak ada, pada class PersonService. sebenarnya yang membedakan apa sich? (Y)

Reply

edwin

about 5 years ago

sebenernya gini bro, onClick$add() itu mirip2 kayak @Listen. Tapi dulu seinget gw belum ada @Listen. Atau mungkin udah ada tapi gw yg engga tau yak, hahaaaa

odeng

about 5 years ago

ok baiklah,,, mw nanya lagi mas, itu kan baru satu windows satu view yach. gimana sich caranya biar, misalkan dalam satu windows viewnya bisa ganti2. misalkan kalo di desktop, kan hanya satu frame truz nanti pake internalFrame yang diletakkan di desktopPan dan diadd ke frame. kalo di zk gimana yach? (C)

Reply

krisna

about 4 years ago

gan tu zk framework belajar dmana?

Reply

edwin

about 4 years ago

Hi Krisna, coba buka2 webnya zkoss deh, dulu sempet baca2 ebooknya juga sih (books.zkoss.org/?)

krisna

about 4 years ago

saya mau tanya lagi gan?,, itu yg @{win$composer.current} @{win$composer.allPersons} dapet dr mana yg gan? masih bingun buat nampilin data ke listboxnya

edwin

about 4 years ago

Hi krisna, allPersons adalah method yg pertama kali di-load sedangkan win$composer.current itu menunjukkan object yg saat itu sedang dipilih

krisna

about 4 years ago

public List findAll() throws Exception { Session session = HibernateUtil.getSessionFactory().openSession(); return (List) session.createCriteria(Person.class).list(); } saya coba coding yg ini tp datanya saya kok tetep gk tampil ya,, apa ada yg kurang di coding saya? :D

bangtiray

about 3 years ago

bang maaf pas di running tampil error sperti ini java.lang.NumberFormatException: For input string: "" java.lang.NumberFormatException.forInputString(Unknown Source) java.lang.Integer.parseInt(Unknown Source) java.lang.Integer.(Unknown Source) org.zkoss.lang.Classes.coerce(Classes.java:1321) org.zkoss.zk.xel.ExValue.coerce(ExValue.java:114) org.zkoss.zk.xel.ExValue.getValue(ExValue.java:109) org.zkoss.zk.ui.metainfo.Property.getValue(Property.java:134) org.zkoss.zk.ui.metainfo.Property.assign0(Property.java:227) org.zkoss.zk.ui.metainfo.Property.assign(Property.java:169) org.zkoss.zk.ui.metainfo.ComponentInfo.applyProperties(ComponentInfo.java:729) org.zkoss.zk.ui.impl.AbstractUiFactory.newComponent(AbstractUiFactory.java:106) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild0(UiEngineImpl.java:857) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild(UiEngineImpl.java:826) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate0(UiEngineImpl.java:735) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate(UiEngineImpl.java:699) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild0(UiEngineImpl.java:872) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild(UiEngineImpl.java:826) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate0(UiEngineImpl.java:735) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate(UiEngineImpl.java:699) org.zkoss.zk.ui.impl.UiEngineImpl.execNewPage0(UiEngineImpl.java:442) org.zkoss.zk.ui.impl.UiEngineImpl.execNewPage(UiEngineImpl.java:356) org.zkoss.zk.ui.http.DHtmlLayoutServlet.process(DHtmlLayoutServlet.java:215) org.zkoss.zk.ui.http.DHtmlLayoutServlet.doGet(DHtmlLayoutServlet.java:136) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Reply

edwin

about 3 years ago

Hi bangtiray, itu kayaknya Integer tapi loe isi String kosong yah?

bangtiray

about 3 years ago

itu permasalahnya bang,,, baru running koq sudah begitu,, hehehe blom input ape2 bang mohon solusi bang

Reply

panji

about 3 years ago

Mas kok kalo di ekstrak ke netbeans package nya error di org nya,Ada cara buat ngatasinya gak mas?

Reply

lobe

about 2 years ago

error bro, gmn ini? type Exception report message Servlet execution threw an exception description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet execution threw an exception org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393) root cause java.lang.NoClassDefFoundError: Could not initialize class com.baculsoft.zk.service.PersonService java.lang.Class.forName0(Native Method) java.lang.Class.forName(Class.java:340) org.zkoss.lang.Classes.forNameByThread(Classes.java:268) org.zkoss.lang.ImportedClassResolver.resolveClass(ImportedClassResolver.java:121) org.zkoss.zk.ui.impl.PageImpl.resolveClass(PageImpl.java:478) org.zkoss.zk.ui.impl.AbstractUiFactory.newComposer(AbstractUiFactory.java:142) org.zkoss.zk.ui.impl.Utils.newComposer(Utils.java:89) org.zkoss.zk.ui.metainfo.ComponentInfo.toComposer(ComponentInfo.java:355) org.zkoss.zk.ui.metainfo.ComponentInfo.toComposers(ComponentInfo.java:323) org.zkoss.zk.ui.metainfo.ComponentInfo.resolveComposer(ComponentInfo.java:310) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild0(UiEngineImpl.java:786) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild(UiEngineImpl.java:778) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate0(UiEngineImpl.java:687) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate(UiEngineImpl.java:651) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild0(UiEngineImpl.java:824) org.zkoss.zk.ui.impl.UiEngineImpl.execCreateChild(UiEngineImpl.java:778) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate0(UiEngineImpl.java:687) org.zkoss.zk.ui.impl.UiEngineImpl.execCreate(UiEngineImpl.java:651) org.zkoss.zk.ui.impl.UiEngineImpl.execNewPage0(UiEngineImpl.java:401) org.zkoss.zk.ui.impl.UiEngineImpl.execNewPage(UiEngineImpl.java:316) org.zkoss.zk.ui.http.DHtmlLayoutServlet.process(DHtmlLayoutServlet.java:215) org.zkoss.zk.ui.http.DHtmlLayoutServlet.doGet(DHtmlLayoutServlet.java:136) javax.servlet.http.HttpServlet.service(HttpServlet.java:618) javax.servlet.http.HttpServlet.service(HttpServlet.java:725) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393) note The full stack trace of the root cause is available in the Apache Tomcat/8.0.3 logs.

Reply

edwin

about 2 years ago

Hi Iobe, itu errornya "java.lang.NoClassDefFoundError", coba scroll error lognya, kali aja nemu error yg lebih detail.

Stef Malo

about 2 years ago

saya dapat error ky gini bang, saat runnig di browser: message No CurrentSessionContext configured! mohon bantuannya bang Edwin. Trims.

Reply

Stef

about 2 years ago

Maaf gan, method allPersonnya ada di class mana y? thanks.

Reply

Stef

about 2 years ago

Update kolom Id Person kok gk bisa y? kolom yg lain bisa....

Reply

edwin

about 2 years ago

halo Stef, id person bukannya primarykey yah?

surya handoko

about 2 years ago

bro , bisa kasih contoh untuk combobox yang join ke table laen gak ? misal table karyawan dengan jabatan misah fk nya di tbl karyawan jabatan_id yg jadi primary key d table jabatan , ane dah coba buat crudnya pake hibernate kalau save oke combobox bisa di pilih dan data bisa masuk k database, cuma pas edit data di kirim ke form event selectItem combobox jabatannya ketika di pilih ada error : Cannot convert com.cjfi.project.entity.Jabatan@4a8a9644 of type class com.cjfi.project.entity.Jabatan to class com.cjfi.project.entity.Jabatan_$$_jvsta03_5 at [file:/C:/Users/surya/Documents/NetBeansProjects/project/target/SpringMVC/WEB-INF/zul/karyawan.zul, line:27] ini script combobox nya Jabatan: kira-kira salah dimana ya , thanks

Reply

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)