Wednesday, April 20, 2011

MVC, duet: Ubuntu, MySQL, Java, Netbeans, Tomcat, ZK, iReport (Part 4)

Create a new project
1. Open the Netbeans
2. Create a new project by opening the menu "File"> "New Project ..." ("ctrl + shift + n"), it will display the "New Project ".
3. In the "Categories", select "Java Web". In the "Projects", select "ZK363 Application". Click the "Next>".
4. Name the project "PFM" and specify the storage location. Click the "Finish".
5. In the window "Project" appears a new project with the name of the PFM. Right-click and select "Properties", then it will appear the window "Project Properties - PFM".
6. In the category "Sources", change "Sources / Binary Format" into the JDK version that the highest (this time JDK6).

7. In the category "Libraries", add the following libraries by pressing the button "Add ...". Library Select "EclipseLink" and "MySQL JDBC Driver. " Press the button "Add JAR / Folder", find "dao-persistence-pfm.jar" and "object-PFM". jar. Remove the two libraries in addition to that, except "ZK3.6.3".
8. In the category of "Run ", select "Server" with the highest version of Tomcat. Change the "contents Path"to "/ PFM"
9. Open the folder where PFM project is saved, open the nbproject folder and open the file "project.properties". Change "war.ear.name = pfm.war" and "war.name = pfm.war"
10. Right click on the "Sources Packages", select "New"> "Java Packages ...". Appear the window "New Java Packages", name with "control", then click the "Finish".

Login Page
View: [ Web Pages/index.zul ]

    <?xml version="1.0" encoding="UTF-8"?>
    <?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" arg0="win" ?>
    <zk xmlns="http://www.zkoss.org/2005/zul">
    <div align="center">
        <window id="win" border="normal" style="margin-top:0px;border-bottom:4px solid gray;border-right:4px solid gray" title="Login" width="400px" apply="control.index">
        <panel>
            <panelchildren>
                <grid>
                    <columns>
                        <column width="150px"/>
                        <column/>
                    </columns>
                    <rows>
                        <row spans="2" align="center">
                           <vbox align="center">
                               <label value="Personal Finance Management" style="font-size:18px;font-weight:bold;color:#1184d4;" />
                               <image src="gambar/pfm.png"/>
                           </vbox>
                        </row>
                        <row>
                            <label value="Nama Login"/>
                            <textbox id="txtboxUserID" width="150px" maxlength="15"/>
                        </row>
                        <row>
                            <label value="Kata Sandi"/>
                            <textbox id="txtboxPassword" width="150px" maxlength="15" type="password"/>
                        </row>
                        <row>
                             <captcha id="cLogin" length="3" width="160px" />
                             <vbox>
                                 <label value="Ketik teks yang muncul di samping" />
                                 <textbox id="txtCaptcha" width="200px" maxlength="3" />
                             </vbox>
                        </row>
                        <row spans="2" align="center">
                            <button id="btnLogin" label="Login" width="120px" image="gambar/login.png" />
                        </row>
                    </rows>
                </grid>
            </panelchildren>
        </panel>
        </window>
    </div>
    </zk>
Controller: [ Sources Package/control/index.java ]
package control;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import objek.md5;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Captcha;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;


public class index extends GenericForwardComposer
{
    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("dao-persistence-pfmPU");
    static EntityManager emTabel    = emf.createEntityManager();


    private Textbox     txtboxUserID,txtboxPassword;
    private Captcha     cLogin;
    private Textbox     txtCaptcha;


    public void onCreate$win()
    {
        txtboxUserID.setFocus(true);
    }


    public void onClick$btnLogin()throws InterruptedException, NoSuchAlgorithmException, NoSuchAlgorithmException, UnsupportedEncodingException
    {
        if ((txtboxUserID.getValue().equals("")) || (txtboxPassword.getValue().equals("")))
        {
            Messagebox.show("User ID dan password tidak boleh kosong.", "Informasi", Messagebox.OK, Messagebox.INFORMATION);
            txtboxUserID.setFocus(true);
            return;
        }
        else if(!cLogin.getValue().equalsIgnoreCase(txtCaptcha.getValue()))
        {
            Messagebox.show("Captcha harus sama dengan yang muncul pada gambar di sebelah kiri", "Informasi", Messagebox.OK, Messagebox.INFORMATION);
            txtCaptcha.setFocus(true);
            txtCaptcha.setSelectionRange(0, 3);
            return;
        }
        else
        {
            listUser        = emTabel.createNamedQuery("Pengguna.findByNamaloginKatasandi")
                                .setHint("eclipselink.refresh", "true")
                                .setParameter("namalogin", txtboxUserID.getValue())
                                .setParameter("katasandi", md5.decode(txtboxPassword.getValue()))
                                .getResultList();
            if (listUser.isEmpty())
            {
                Messagebox.show("Pengguna " + txtboxUserID.getValue() + " belum terdaftar atau kata sandi salah", "Informasi", Messagebox.OK, Messagebox.INFORMATION);
                txtboxUserID.setFocus(true);
                return;
            }
        }
        session.setAttribute("userid", txtboxUserID.getValue());
        session.setAttribute("id", ((Pengguna) listUser.get(0)).getIdpengguna());

        Executions.sendRedirect("utama.zul");
    }


    //Zul Object
    protected List  listUser;
}
Addition:
1. Add this script
@NamedQuery (name = "Pengguna.findByNamaloginKatasandi", query = "SELECT p FROM Pengguna p WHERE p.katasandi = :katasandi and p.namalogin = :namalogin")
to "dao-persistence-pfm/dao/Pengguna.java", then save.2. Right-click the project "persistence-PFM-dao", then select "Clean and Build". Right-click the project "PFM", then select "Clean", so the library in the project "PFM" will use newest "dao-persistence-PFM". 3. Create a folder on the "Web Pages" with the name "images". Copy images "login.png" and "pfm.png" into the folder "images" Explanation: 1. In the "Web Pages / index.zul" there is a line
<?xml version="1.0" encoding="UTF-8"?>
that state the xml structure version used in "index.zul". Next code
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" arg0="win" ?>
is the code needed to allow annotation and linking / mapping with the "Package Sources / control / index.java", which is written on the attribute "apply" in the "window". Attributes "arg0" contains "win", so that the attribute "id" in the "window" contains a "win" as below
<window id="win" border="normal" style="margin-top:0px;border-bottom:4px solid gray;border-right:4px solid gray" title="Login" width="400px" apply="control.index">
Do not erase line 1 to 3.
2. In "Sources Package/control/index.java" there is

public class index extends GenericForwardComposer
that simplify the writing of code in the "index.java", because developers do not need to write how to connect / map with the controls that exist in the "Web Pages / index.zul", but simply by writing
private Textbox     txtboxUserID, txtboxPassword;
because in the "Web Pages / index.zul" there is a "textbox" which has the id "txtboxUserID" and "txtboxPassword". However, there is no obligation to declare all the controls that exist, just the controls that needed it. Could be, there is no control that is declared.
3. In "Sources Package / control / index.java" there is

static EntityManagerFactory emf = Persistence.createEntityManagerFactory ("dao-persistence-pfmPU");
static EntityManager emTabel = emf.createEntityManager ();
to connect to the database. "dao-persistence-pfmPU" is the name of the connection there at the time of making connections in the project "persistence-PFM-dao", but if not remember his name, can be seen in "dao-persistence-pfm/Source Packages / META-INF / persistence . xml ".
4. At the "Package Sources / control / index.java" there is

public void OnCreate$win()
...
public void onClick$btnLogin()throws InterruptedException
which is a catcher event that occurred in controls. Events that can be used depending on the control used. "OnCreate $ win" will run at a time "win" (control: window) is created (create). "onClick $ btnLogin" run at "btnLogin" (control: button) is clicked. At the "Package Sources / control / index.java"unnecessary variable declaration to "win" and "btnLogin", because indeed they are only used for the event just so pretty used to the method. "throws InterruptedException" is inherited from the "Messagebox".
5. At the "Package Sources / control / index.java" there is

listUser=emTabel.createNamedQuery("Pengguna.findByNamaloginKatasandi")
                .setHint("eclipselink.refresh", "true")
                .setParameter("namalogin", txtboxUserID.getValue())
                .setParameter("katasandi", md.encode(txtboxPassword.getValue().getBytes()))
                .getResultList();
that alternatif way to get data from database. That line use namedquery in "dao-persistence-pfm/Source Packages/dao/Pengguna.java"
@NamedQuery(name = "Pengguna.findByNamaloginKatasandi", query = "SELECT p FROM Pengguna p WHERE p.katasandi = :katasandi and p.namalogin = :namalogin")
"namalogin" parameter will fill ":namalogin", in the other hand "katasandi" parameter will fill ":katasandi". As note, the date tipe of the parameter must be same. Returned value by "emTabel.createNamedQuery("Pengguna.findByNamaloginKatasandi")" is a list from "Pengguna" object.
6. If all condition fulfill, then login page save data to the session

session.setAttribute("userid", txtboxUserID.getValue());
and will redirect to other page
Executions.sendRedirect("zul/menuutama.zul");
Main Page
View: [ Web Pages/utama.zul ]
<?xml version="1.0" encoding="UTF-8"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" arg0="win" ?>
<zk xmlns="http://www.zkoss.org/2005/zul">
<window id="win" border="normal" width="100%" height="100%" apply="control.utama">
    <div height="45px" style="background-color:teal">
        <vbox>
            <label value="Personal Finance Management" style="font-size:14px;font-weight:bold;color:#ffffff;"/>
            <hbox align="center">
                <label value="Anda Login Sebagai: " />
                <label id="lblUser" value="" />
            </hbox>
        </vbox>
    </div>
    <menubar style="margin-bottom:5px" zindex="0">
        <menuitem label="Home" href="home.html" image="gambar/rumah.png" target="iFrameData" />
        <menu label="Data Induk" image="gambar/proses.png">
            <menupopup>
                <menuitem label="Transaksi" href="transaksi.zul" image="gambar/formulir.png"  target="iFrameData" />
                <menuseparator />
                <menu label="Laporan" image="gambar/folder.png" >
                    <menupopup>
                        <menuitem label="Rekap Transaksi" href="laporan/rekap.zul" target="iFrameData" image="gambar/formulir.png" />
                    </menupopup>
                </menu>
            </menupopup>
        </menu>
        <menuitem id="mnLogout" label="Logout" image="gambar/logout.png" />
    </menubar>
    <iframe name="iFrameData" width="100%" height="88%"/>
</window>
</zk>
Controller: [ Sources Package/control/utama.java ]
package control;


import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Label;
import org.zkoss.zul.Window;
public class utama extends GenericForwardComposer
{
    private Label       lblUser;
    private Window      win;
  
    public void onCreate$win()
    {
        if (Sessions.getCurrent().getAttribute("userid") == null)
        {
            win.detach();
            win = null;
            execution.sendRedirect("../index.zul", "_top");
            return;
        }
  lblUser.setValue(session.getAttribute("userid").toString());
    }
  
    public void onClick$mnLogout()
    {
        session.invalidate();
        execution.sendRedirect("index.zul", "_top");
    }
}
Addition:
Copy image "rumah.png", "formulir.png", "folder.png", and "logout.png" to folder "gambar"
Explanation:
1. In "Sources Package/control/utama.java" there is
if (Sessions.getCurrent().getAttribute("userid") == null)
to check if the page is opened after login or not.
2. In "Sources Package/control/utama.java" there is
session.invalidate();
to delete the session.

No comments:

Post a Comment