Creating a Simple Sightseeing Application

From Documentation

Before You Start

Translations are available in Français and Português.

Other tutorials

Introduction

This tutorial aims to use a simple example to demonstrate how to implement a ZK application. You could try the application on line first before keep reading.

Our sample application is a sightseeing web site that uses Google Maps. UI has three parts:

  • A list box: show every resort spots and allow the user to pick up for detailed information
  • Google Maps: display the location of the selected resort spot.
  • Detail pane: show detailed information of the selected resort spot.

Resort-s.jpg

We'll show two ways to build an Ajax-enabled Web application using ZK: a straightforward way that manipulates data beans manually, and an automatic way by use of ZK data binding.

Preparing

We can create a simple data model with Java class first because we will use this model later. The data model consists of the following attributes: name, description, latitude, and longitude.

public class Resort {
    private String _name;
    private String _description;
    private double _latitude;
    private double _longitude;
    
    public Resort() {
    }

    public Resort(String name, String description, double latitude, double longitude) {
        _name = name;
        _description = description;
        _latitude = latitude;
        _longitude = longitude;
    }

    // getter and setter methods are omitted.

    public static List<Resort> getAll() {
       // Details are omitted.
    }
}

A Straightforward Way

This section will introduce the first implementation. We call it the straightforward way since the application will manipulate the data model directly in Java. It is a common practice found in most frameworks. In the next section will introduce another implementation that use ZK data binding to manipulate the data model automatically.

Design User Interface Page Using ZK Markup Language

We first develop the application's view page file: resort.zul. It includes three components: listbox, gmaps (Google Maps), and groupbox (detailed pane).

To have better separation of UI and business logic, there is no Java code or scriplets in resort.zul. All business logic are defined in a separate Java file — ResortController.java.

The interaction between the zul file and the Java file is triggered by a user's activities. When a user selects an item in the list box, an onSelect event will be fired, and the refreshUI() method of ResortController.java will be invoked to display the selected item on the Google Maps, and to show the coordinates of selected item.

<!-- resort.zul -->
<?script 
  content="zk.googleAPIkey='ABQIAAAACZ90QS5pNiEvbXhI0k2NLRTGXUEQDrMr1bP0DVG8X36ZVCheaRQMK05Rsdneh4skNF6KXaLI8maLlA'"?>

<window id="win" title="ZK Tutorial" border="normal"
 apply="org.zkforge.resort.ui.ResortController">
	<hbox>
		<listbox id="lb" hflex="1">
			<listhead sizable="true">
				<listheader label="Name" width="100px"/>
				<listheader label="Description"/>
			</listhead>
		</listbox>	
		<gmaps id="gmap" zoom="16" showTypeCtrl="true" mapType="satellite" 
                  showLargeCtrl="true" width="610px" height="400px">
			<ginfo id="ginfo"/>
		</gmaps>
	</hbox>
	<groupbox id="gb" mold="3d" width="100%">
		<caption label="Resort"/>
		Name:<textbox disabled="true" id="name"/>
		Description:<textbox disabled="true" id="desc"/>
		Longitude:<doublebox disabled="true" id="longtitude"/>
		Latitude:<doublebox disabled="true" id="latitude"/>
	</groupbox>
</window>

Manipulate UI Components Using Java

In the Java file(ResortController.java), we retrieve the UI components by their id, and put the data of the selected item into them. Then, ZK engines will update the web page in Ajax automatically. Furthermore, we could allow users to modify the data bean without adding a single line of Java code.

// ResortController.java
public class ResortController extends GenericForwardComposer {

    private static final long serialVersionUID = -4023064279380075239L;
    private Listbox lb;
    private Gmaps gmap;
    private Ginfo ginfo;
    private Textbox name;
    private Textbox desc;
    private Doublebox latitude;
    private Doublebox longtitude;

    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        
        lb.setItemRenderer(new ListitemRenderer() {
            public void render(Listitem item, Object data) throws Exception {
                Resort value = (Resort)data;
                item.appendChild(new Listcell(value.getName()));
                item.appendChild(new Listcell(value.getDescription()));
                item.setValue(value);
            }
        });
        
        lb.setModel(new ListModelList(Resort.getAll()));
    }
    
    public void onSelect$lb() {
        refreshUI();
    }

    private void refreshUI() {
        Resort resort = (Resort) lb.getSelectedItem().getValue();
        double latitudeValue = resort.getLatitude().doubleValue();
        double longtitudeValue = resort.getLongitude().doubleValue();
        
        name.setValue(resort.getName());
        desc.setValue(resort.getName());
        latitude.setValue(resort.getLatitude());
        longtitude.setValue(resort.getLongitude());
        ginfo.setLat(latitudeValue);
        ginfo.setLng(longtitudeValue);
        ginfo.setContent(resort.getDescription());
        gmap.panTo(latitudeValue, longtitudeValue);
        gmap.setZoom(16);
        gmap.openInfo(ginfo);
    }
}

This example illustrates the simplicity of building an Ajax-enabled web application with ZK. The "View" and "Controller" are cleanly separated, and no JavaScript code is required! We believe that the best way to use Ajax is to not have to know of its existence.

An Automatic Way (With Data Binding)

To simplify the job of maintaining the consistency of data between the data bean and the user interface, ZK provides the mechanism of data-binding. You simply define the relations between the "Model" (data beans) and the "View" (UI components), and ZK's data-binding feature will maintain the data consistency between them automatically.

Define Relations between Data Bean and UI Components

One simple way is to directly define such relations in the web page. One of the major differences is that we add another data bean which represents the selected item, and then bind all of related ZK components to it.

<!-- resort_databind.zul -->
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" ?>
<?script 
  content="zk.googleAPIkey='ABQIAAAACZ90QS5pNiEvbXhI0k2NLRTGXUEQDrMr1bP0DVG8X36ZVCheaRQMK05Rsdneh4skNF6KXaLI8maLlA'" ?>

<window id="win" 
  apply="org.zkforge.resort.ui.ResortController2" title="ZK Tutorial" width="1024px" border="normal">
	<hbox>
	<listbox id="lb" model="@{win$ResortController2.resorts}" selectedItem="@{win$ResortController2.selected}">
		<listhead sizable="true">
			<listheader label="Name" width="100px"/>
			<listheader label="Description"/>			
		</listhead>
		<listitem self="@{each=resort}">
			<listcell label="@{resort.name}" />
			<listcell label="@{resort.description}" />			
		</listitem>
	</listbox>	
	<gmaps id="gmap" zoom="16" showTypeCtrl="true" mapType="satellite" 
          showLargeCtrl="true" width="610px" height="400px">
		<ginfo id="ginfo" />
	</gmaps>
	</hbox>
	<groupbox id="gb" mold="3d" width="100%">
		<caption label="Resort"/>
		Name:<textbox id="name" value="@{win$ResortController2.selected.name}" disabled="true"/>
		Description:<textbox  id="desc" value="@{win$ResortController2.selected.description}" disabled="true"/>
		Longitude:<doublebox id="lng" value="@{win$ResortController2.selected.longitude}" disabled="true"/>
		Latitude:<doublebox id="lat" value="@{win$ResortController2.selected.latitude}" disabled="true"/>	
	</groupbox>
</window>

Revise the Java File

With the help of data-binding, the handling codes in ResortController.java are much reduced. Once the user selects a different item, the data bean will be changed, and then data of all related ZK components will be updated automatically.

// ResortController2.java
public class ResortController2 extends GenericForwardComposer {

    private static final long serialVersionUID = -7504093487870918898L;
    private List<Resort> _resorts;
    private Resort _selected;
    private Gmaps gmap;
    private Ginfo ginfo;

    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        setResorts(Resort.getAll());
        _selected = new Resort();
    }
    
    public void onSelect$lb() {
        refreshUI();
    }

    private void refreshUI() {
        double latitude = _selected.getLatitude().doubleValue();
        double longtitude = _selected.getLongitude().doubleValue();
        
        ginfo.setLat(latitude);
        ginfo.setLng(longtitude);
        ginfo.setContent(_selected.getDescription());
        gmap.panTo(latitude, longtitude);
        gmap.setZoom(16);
        gmap.openInfo(ginfo);
    }

    public Resort getSelected() {
        return _selected;
    }

    public void setSelected(Resort selected) {
        _selected = selected;
    }

    public void setResorts(List<Resort> _resorts) {
        this._resorts = _resorts;
    }

    public List<Resort> getResorts() {
        return _resorts;
    }
}

Installing the Web Application

  1. Install Java SDK
    If you haven't already done so, please download and install Java SDK.
  2. Install a Servlet Container
    If you don't already have a Servlet container, please download and install Apache Tomcat.
  3. Download the Web Application
    Download this application's files here.
  4. Unzip the file
    Unzip resort.zip, and copy resort.war to $TOMCAT_HOME/webapps/.
  5. Start your Web Server, and point your browser to: http://localhost:8080/resort/resort.zul

Last Update : 2010/09/30