Get ZK Up and Running with MVC"

From Documentation
 
(413 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Template:UnderConstruction}}
 
 
 
= Introduction =
 
= Introduction =
 
 
This tutorial is targeted to software developers. We will teach you how to build a modern web application with ZK. The target application we are going to build is a bookstore catalog application.
 
 
This application has 2 main functions:
 
# Search books by book name keyword
 
# View a book's details
 
 
 
[[File:tutorial-searchexample.png]]
 
 
You can take look at [http://www.zkoss.org this application's live demo].
 
 
We also provide the complete source code with an Eclipse project zip file, please refer to [[Download]].
 
 
<!--
 
<!--
 
target readers
 
target readers
Line 21: Line 5:
 
-->
 
-->
  
= Installation =
 
  
In this section, we'll tell you how to setup up ZK in a web application project.
+
This tutorial is intended for software developers who have experience in writing Java programs. You will learn basic concepts by building a modern web application with ZK. The target application we are going to build is a simple car catalog application.  We will use the '''MVC''' approach to build the application here. This approach is very intuitive and flexible and gives you full control of components. In addition, you can also choose to go with the '''MVVM''' approach that is covered in [[ZK Getting Started/Get ZK Up and Running with MVVM| Get ZK Up and Running with MVVM]].
  
== Prerequisite ==
+
<!--
 +
take look at the [http:// target application's live demo] and
 +
-->
 +
You can download the complete source code under the [[#Start from Example Project| Start from Example Project]] section.
  
We use Eclipse IDE 3.7 (indigo) for Java EE developer ([http://www.eclipse.org/downloads/packages/release/indigo/sr2 Download it]) to demonstrate the whole instructions.
 
  
=== Add a Server Runtime Environment ===
 
  
A web application project needs an application server environment to run. In Eclipse menu, select '''Window \ Preferences''', in Preferences window, select '''Server\Runtime Environments'''. Click '''Add''' button to add a server runtime environment.
+
{{Template:tutorial common chapters}}
  
[[File:Tutorial-addruntime.png]]
+
= Handling UI Logic =
 +
<!--
 +
In this chapter, you'll learn:
  
 +
# How to handle a component's event
 +
# How to control components in a controller
 +
# How to use a template
 +
-->
  
 +
The next step after building the UI is to make it respond to user interaction. The pattern we introduce here is to '''control ZK components directly by their API'''. We call this [[ZK Developer's Reference/MVC|'''Model-View-Controller''' ('''MVC''') design pattern]]. This pattern divides an application into 3 parts.
  
Select Apache Tomcat v6.0 as our environment, click '''Next'''.
+
The '''Model''' consists of application data and business rules. <code>CarService</code> and other classes used by it represent this part in our example application.  
  
[[File:Tutorial-tomcat.png]]
+
The '''View''' indicates the user interface. The zul page which contains ZK components represents this part. A user's interaction with components triggers events to be sent to controllers.  
  
 +
The '''Controller''' plays the role of a coordinator between View and Model. It receives events from View to update Model and retrieves data from Model to change View's presentation.
  
 +
== The Flow to Handle a User Action ==
 +
[[File:tutorial-mvc.png | center]]
  
If you have installed Tomcat before, just provide your path. If you don't, just click '''Download and Install''' button and choose a folder, wait for a while, Eclipse will download and install Tomcat for you. After installation is complete, the '''Finish''' button will become enabled. Click it to finish adding server runtime.
+
# When a user interacts with a component (e.g. click a button) on a ZUL, the user action triggers an event.
 +
# This event is sent to the controller and invokes the corresponding event listener method.
 +
# The event listener method usually contains business logic, accesses data, and the logic to manipulate ZK components.
 +
# A component's state change is responded to a browser, and ZK client updates the corresponding UI.
  
[[File:Tutorial-downloadinstall.png]]
 
  
  
 +
== Creating UI Controllers==
  
You shall see a entry like the following in your '''Server Runtime Environment'''.
+
===Extending SelectorComposer ===
 +
In ZK, the controller is responsible for controlling ZK components and listening to events triggered by user interaction. We can create such a controller class by simply extending [https://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/select/SelectorComposer.html SelectorComposer] :
  
[[File:tutorial-runtimeEnvironment.png]]
+
<syntaxhighlight line lang="java">
 +
package tutorial;
  
 +
// omit import for brevity
  
=== Create a Web Project ===
+
public class SearchController extends SelectorComposer<Component> {
  
In Eclipse, select '''File \ New \ Dynamic Web Project''', enter '''zktutorial''' in Project name, select 2.4 for '''Dynamic web module version''' and keep every thing else default.
+
}
 +
</syntaxhighlight>
  
[[File:Tutorial-newproject.png]]
+
===Apply a Controller to a UI Component===
 +
After a controller is created, we associate it with its corresponding UI component. Associating a controller with a component is just specifying a fully-qualified class name for the target component's <code>apply</code> attribute. The following code shows how to associate a controller with a <code><window></code>.
  
== Download ==
+
'''Extracted from [https://github.com/zkoss/zkbooks/blob/master/gettingStarted/getZkUp/src/main/webapp/searchMvc.zul searchMvc.zul]'''
 +
<syntaxhighlight lang="xml"  highlight='2' line>
 +
<window title="Search" width="600px" border="normal"
 +
apply="tutorial.SearchController">
 +
<!-- omit other components for brevity -->
 +
</window>
  
[http://www.zkoss.org/download/zk Download the ZK CE ] (file name should be ''zk-bin-6.0.0.zip'') and extract it to a folder.
+
</syntaxhighlight>
  
== Add ZK JAR to Your Project==
 
  
To use ZK in your project, you have to add ZK JAR into your project's library folder.
+
After associating the controller with the ''window'' component, the controller can listen to events sent from UI and retrieve components which allows us to implement the application's feature. Let's start from the "search car": a user enters a keyword, clicks the "Search" button to trigger the search.  
  
Copy JAR files under following list to '''zktutorial/WEB-INF/lib''':
+
Steps to implement an application feature:
* {YOUR_ZK_UNZIP_FOLDER}/dist/lib
+
# Declare a method that listens to a component's event
* {YOUR_ZK_UNZIP_FOLDER}/dist/lib/ext
+
# Control UI components to implement presentation and business logic in the listener method
  
If your project use maven, please add following dependencies:
+
== Listening to User Actions ==
  
<source lang="xml">
+
When we apply a controller to a component, every event triggered by this component (and its child components) is sent to the controller. If we register an event listener for the triggered event, ZK will invoke the listener.
<dependency>
 
<groupId>org.zkoss.zk</groupId>
 
<artifactId>zkbind</artifactId>
 
<version>6.0.0</version>
 
</dependency>
 
  
</source>
+
Since a user clicks "Search" button to trigger the search function, we have to register a listener method, <code>search()</code>, to "Search" button's <code>onClick</code> event with the following annotation:
  
== Configure web.xml ==
+
<code> @Listen("[EVENT_NAME] = #[COMPONENT_ID]")</code>
  
By default, Eclipse creates a default web.xml under '''[PROJECT_NAME]/WebContent/WEB-INF'''. You just add line 15 to 42 of the following sample web.xml to your project and the configuration is complete.
+
For complete selector syntax, please refer to [http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/select/SelectorComposer.html SelectorComposer javadoc].
  
<source lang="xml" high="4,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42">
+
The final code looks like:
  
<?xml version="1.0" encoding="UTF-8"?>
+
<syntaxhighlight lang="java" highlight="3" line>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
+
public class SearchController extends SelectorComposer<Component> {
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">  
 
  
<display-name>zktutorial</display-name>
+
@Listen("onClick = #searchButton")
<welcome-file-list>
+
public void search(){
<welcome-file>index.zul</welcome-file>
 
<welcome-file>index.zhtml</welcome-file>
 
<welcome-file>index.html</welcome-file>
 
<welcome-file>index.htm</welcome-file>
 
</welcome-file-list>
 
 
    <!-- ZK -->
 
    <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>
+
</syntaxhighlight>
        <servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>
+
* Line 3: <code>searchButton</code> is the button's id specified in the zul, and you can find it in the previous zul. For complete selector syntax, please refer to [http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/select/SelectorComposer.html SelectorComposer javadoc].
    </servlet>
+
* Line 4: Event listener must be a public method.
    <servlet-mapping>
 
        <servlet-name>auEngine</servlet-name>
 
        <url-pattern>/zkau/*</url-pattern>
 
    </servlet-mapping>
 
  
</web-app>
+
== Controlling UI Components ==
  
</source>
+
After establishing the relationship between an event and an event listener method, we can start to implement application logic with components. But firstly we need to retrieve/wire the UI component's object by annotating '''<code>@Wire</code>''' on controller's member variables. Because ZK instantiates a page's components object according to the zul, you should get ZK-created component objects instead of calling <code>new Window()</code> manually.
* Line 4: this sample is for Servlet 2.4. There are other samples for [[ZK_Installation_Guide/ZK_Background/Sample_of_web.xml_for_Servlet_2.3|Servlet 2.3]] and [[ZK_Installation_Guide/ZK_Background/Sample_of_web.xml for Servlet 3.0| Servlet 3.0]]
 
  
== Verify Installation ==
+
<!--
 +
<div style="float:left;width:80px">
 +
[[File:Icon-steps.png]]
 +
</div>
 +
-->
 +
Steps to retrieve components:
 +
# Declare a variable with target component type (e.g. <code>Listbox</code>, <code> Label</code>...)
 +
# Name the variable as component's ID.
 +
#: Matching ID is the default rule to match a component for <code>@Wire</code>, and please refer to [[ZK Developer's Reference/MVC/Controller/Wire Components| Wire Components in Developer's Reference]] to know other ways.
 +
# Annotate the variable with <code>@Wire</code>.
  
After installation, you can create a simple zul to verify the installation works or not. In Eclipse, select '''File / New / File''' or '''File / New / Other / File''' to add a new file, '''hello.zul''', under '''WebContent'''. Copy and paste the following sample code into hello.zul and save it.
 
  
 +
Then ZK will "wire" a corresponding ZK component object to the variable we declared. After this has been done, we can then control and manipulate UI by accessing those annotated member variables.
  
'''hello.zul'''
+
<syntaxhighlight line lang="java" highlight="3,4,5,6">
<source lang="xml">
 
<window title="My First ZK Application" border="normal">
 
Hello World!
 
</window>
 
</source>
 
  
 +
public class SearchController extends SelectorComposer<Component> {
  
 +
@Wire
 +
private Textbox keywordBox;
 +
@Wire
 +
private Listbox carListbox;
  
=== Add a Server in Eclipse ===
+
//other codes...
 +
}
 +
</syntaxhighlight>
 +
* Line 5-6: In searchMvc.zul, there is a ''listbox'' whose id is carListbox. ZK will make the variable <code>carListbox</code> reference to the ''listbox'' object after components are created.
  
Right click on your project root folder, in context menu, select '''Run As / Run on Server''' to run this project on an application server.
 
  
[[File:Tutorial-runonserver.png]]
+
The search method performs the logic: call <code>CarService</code> to search with a keyword and set result list to <code>Listbox</code>.
  
 +
You can get a component's state in a browser with its getter methods, <code>getValue()</code>, or change a component's state like making a <code>Label</code> invisible with setter, <code>setVisible(false)</code>, to achieve some dynamic UI effect.
  
 +
<syntaxhighlight line lang="java" highlight="8">
 +
public class SearchController extends SelectorComposer<Component> {
 +
//omit codes to get components
  
If you have defined servers before, choose an existing server. If you don't, select '''Manually define a new server''' and select '''Tomcat v6.0 Server''' as we previously installed server runtime environment. Then click "Finish" and you can see a "Tomcat v6.0 Server" item in the Servers view.  
+
@Listen("onClick = #searchButton")
 
+
public void search(){
[[File:Tutorial-newserver.png]]
+
String keyword = keywordBox.getValue();
 
+
List<Car> result = carService.search(keyword);
 
+
carListbox.setModel(new ListModelList<Car>(result));
 
+
}
If your Eclipse contains only one dynamic web project, that project should already be configured to deploy on Tomcat you just created. If there is no project under your Tomcat server, you still can add your web project manually. Right click Tomcat server, select '''Add and Remove...'''. Select your project from left side "Available", click "Add >"  button to add a project to deploy on Tomcat server.
+
}
 
+
</syntaxhighlight>
[[File:Tutorial-addproject.png]]
+
* Line 6: We can easily get what keyword a user inputs by <code>keywordBox.getValue()</code>
 
+
* Line 8: Notice that <code>setModel()</code> only accepts a <code>ListModel</code> object, so we can use <code>org.zkoss.zul.ListModelList</code> to wrap search result list. There are other <code>ListModel</code> objects for different collection types, please refer to [[ZK Developer's Reference/MVC/Model/List Model| List Model in Developer's Reference]]. To change data item displayed in a <code>Listbox</code>, call <code>carListbox.setModel()</code>. The model of a component is the data the component holds and we can change the model to change the data rendering on the screen, please refer to [[ZK_Developer%27s_Reference/MVC/Model#Model-Driven_Rendering| Model-Driven Rendering]]
 
 
 
 
 
 
You can see a jar icon with project name under your Tomcat server. That means zktutorial is configured to deploy on Tomcat v6.0.
 
  
[[File:Tutorial-serverview.png]]
+
==Displaying a Data Collection ==
  
  
 +
We have successfully made clicking "Search" button to invoke its corresponding event listener, but we would still find that content of ''listbox'' doesn't show the search result correctly. That is because we haven't specified how to render data model on the ''listbox''. Now, we will use a special tag, [[ZK Developer's Reference/MVC/View/Template |<template>]], to control the rendering of each car. ZK will render each object in the data model according to components inside <code><template/></code>.
  
 +
Steps to use <code><template></code>:
 +
# Use <code><template></code> to enclose components that we want to create repeatedly.
 +
# Set template's <code>name</code> attribute with <code>model</code>.
 +
# Use implicit variable, <code>each</code>, to assign domain object's properties to component's attributes.
  
Eclipse let users to start, stop, and deploy a web application to an application server through "Servers" view. Click start icon to start server or right click on zktutorial root folder and select  '''Run As / Run on Server''' to run the project.
+
Please refer to [[ZK Developer's Reference/MVC/View/Template/Listbox Template]] for more details.
  
[[File:Tutorial-startserver.png]]
+
'''Extracted from [https://github.com/zkoss/zkbooks/blob/master/gettingStarted/getZkUp/src/main/webapp/searchMvc.zul searchMvc.zul]'''
 +
<syntaxhighlight lang="xml" highlight="1,7,8,9,10,11,12,13" line>
 +
<listbox id="carListbox" rows="3" emptyMessage="No car found in the result">
 +
    <listhead>
 +
        <listheader label="Model" />
 +
        <listheader label="Make" />
 +
        <listheader label="Price" width="20%"/>
 +
    </listhead>
 +
    <template name="model">
 +
        <listitem>
 +
            <listcell label="${each.model}"/>
 +
            <listcell label="${each.make}"/>
 +
            <listcell label="${('$'+=each.price)}"/>
 +
        </listitem>
 +
    </template>
 +
</listbox>
 +
</syntaxhighlight>
 +
* Line 1: Specify <code>rows</code> to limit how many rows to display for the Listbox, so that you don't have to measure its height in pixel.
 +
* Line 7: The template tag should be put inside the listbox.
 +
* Line 8: The <code><listitem></code> in previous section is for static data, we should replace it with current code.
 +
* Line 9: The "each" is a variable that references to a domain object in the model list which is <code>Car</code> in our example application. We can use it to access domain object's property with EL, e.g. <code>${each.price}</code>.
 +
* Line 11: Concatenate 2 strings with [[ZK_Developer%27s_Reference/UI_Composing/ZUML/EL_Expressions#EL_3.0_Support| EL 3 syntax]]: <code>(+=)</code>
  
 +
== Implementing "View Car Details" ==
  
 +
The previous sections describe the basic steps to implement a feature. Let's recap them by implementing "view car details":
  
Open your browser to visit http://localhost:8080/hello.zul. If you can see the following image, then your installation is success.
+
First, declare a method to listen to <code>onSelect</code> event of <code>Listbox</code> with <code>@Listen</code>.
  
[[File:Tutorial-hello.png]]
+
Second, use <code>@Wire</code> to get UI components like previewImage, modelLabel, priceLabel, and descriptionLabel and assign value to them with setter.
  
= The Domain in This Tutorial =
+
[https://github.com/zkoss/zkbooks/blob/master/gettingStarted/getZkUp/src/main/java/tutorial/SearchController.java SearchController.java]
 +
<syntaxhighlight lang="java" line>
  
Our target application is a bookstore catalog that allows users to search and view book's detail including name, price, description, and cover preview. The following is the domain object that represents a book.
+
public class SearchController extends SelectorComposer<Component> {
  
<source lang="java">
+
@Wire
 +
private Listbox carListbox;
 +
@Wire
 +
private Label modelLabel;
 +
@Wire
 +
private Label makeLabel;
 +
@Wire
 +
private Label priceLabel;
 +
@Wire
 +
private Label descriptionLabel;
 +
@Wire
 +
private Image previewImage;
  
public class Book {
+
@Listen("onSelect = #carListbox")
private Integer id;
+
public void showDetail(){
private String name;
+
Car selected = carListbox.getSelectedItem().getValue();
private String thumbnail;
+
previewImage.setSrc(selected.getPreview());
private String description;
+
modelLabel.setValue(selected.getModel());
private Float price;
+
makeLabel.setValue(selected.getMake());
//omit getter and setter for brevity
+
priceLabel.setValue(selected.getPrice().toString());
 +
descriptionLabel.setValue(selected.getDescription());
 +
}
 +
//omit other codes for brevity
 
}
 
}
</source>
+
</syntaxhighlight>
 
+
* Line 16: register an <code>onSelect</code> event listner on the <code>Listbox</code>
 
+
* Line 18: get user-selected item.
Then we can define a service class to perform the business logic (search books) as follows:
+
* Line 19~23: publish the selected car detail to the browser by setter methods.
 
 
<source lang="java">
 
public interface BookService {
 
 
 
/**
 
* Retrieve all books in the bookstore.
 
* @return all books
 
*/
 
public List<Book> findAll();
 
 
/**
 
* search books according to keyword.
 
* @param keyword book name's keyword
 
* @return list of book that match the keyword
 
*/
 
public List<Book> search(String keyword);
 
}
 
</source>
 
 
 
=Sketch User Interface =
 
 
 
Design UI is a good step to start building an application. In ZK, you can use a XML-formatted language, ZK User Interface Markup Language (ZUML) <ref> [[ZUML Reference|ZUML Reference]] </ref>,  to describe user interface. Each XML element represents a component and its attributes are used to set the component's property. For example, the following code creates a window with specified title and normal border and it has a child component, label.
 
 
 
<source lang="xml">
 
<window title="My First ZK Application" border="normal">
 
    <label value="Hello"/>
 
</window>
 
</source>
 
 
 
 
 
ZK components are like building blocks, and each component's style, behavior, and function can be configured. You can combine existing components to construct your desired UI. Basically, our target application's user interface is divided into 3 areas inside a window, they are (from up to down) search, listbox, and detail.
 
 
 
 
 
<div style="border-style:dashed;border-width:1px;width:80px;text-align:center;">
 
search
 
</div>
 
<div style="border-style:dashed;border-width:1px;width:80px;text-align:center;">
 
listbox
 
</div>
 
<div style="border-style:dashed;border-width:1px;width:80px;text-align:center;">
 
detail
 
</div>
 
 
 
 
 
The following is the complete code of our target application UI:
 
 
 
'''searchMvc.zul'''
 
<source lang="xml">
 
 
 
<window title="Search Product" width="800px" border="normal"
 
style="padding-top:10px;padding-left:10px;" apply="tutorial.SearchProductComposer">
 
<vlayout>
 
<hlayout>
 
<textbox id="keywordBox" />
 
<button id="searchButton" label="search" image="img/search.png" />
 
</hlayout>
 
<listbox id="productListbox" mold="paging" pageSize="5">
 
<listhead>
 
<listheader label="Name" />
 
<listheader label="Price" />
 
</listhead>
 
<template name="model">
 
<listitem>
 
<listcell label="${each.name}"></listcell>
 
<listcell>$<label value="${each.price}" /></listcell>
 
</listitem>
 
</template>
 
</listbox>
 
<separator bar="true" height="10px" />
 
<hbox id="detailArea">
 
<image id="thumbImage" width="250px" />
 
<vlayout>
 
<label id="nameLabel" />
 
<label id="priceLabel" />
 
<label id="descriptionLabel" style="display:inline" />
 
</vlayout>
 
</hbox>
 
</vlayout>
 
</window>
 
</source>
 
 
 
= Manipulate UI =
 
 
 
The next step after sketching the UI is to make UI interact with user. We change the UI dynamically by controlling UI component Java object directly.
 
 
 
== UI Controller==
 
 
 
In order to control UI, you have to create a controller class.
 
 
 
== Stuff a bunch of data ==
 
 
 
We hope users can see a list of books when the page shows up.
 
 
 
 
 
== Handling User Action ==
 
 
 
When users select a listitem, we should show them the detail.
 
 
 
= Bind UI Automatically =
 
== Binding data ==
 
== Handling UI commands ==
 
 
 
 
 
= Patterns Comparison =
 
== MVC v.s MVVM==
 
=== When to use ===
 
=== Restriction ===
 
 
 
= Unit Test ZK Application =
 
 
 
ZK provides a unit test library, ''Mimic'', which is one module of ''ZK Application Test Suite'' (ZATS).
 
 
 
= Deploy and Run =
 
  
  
= Reference =
 
  
<references/>
+
{{Template:tutorial Approach Comparison}}

Latest revision as of 10:27, 10 January 2022

Introduction

This tutorial is intended for software developers who have experience in writing Java programs. You will learn basic concepts by building a modern web application with ZK. The target application we are going to build is a simple car catalog application. We will use the MVC approach to build the application here. This approach is very intuitive and flexible and gives you full control of components. In addition, you can also choose to go with the MVVM approach that is covered in Get ZK Up and Running with MVVM.

You can download the complete source code under the Start from Example Project section.


Tutorial Objective

Our target application is a simple car catalog application. This application has two functions:

  1. Search cars.
    Enter a keyword in the input field, click Search and search results will be displayed in the car list below.
  2. View details.
    Click an item from the car list, the area below the car list will show the selected car's details including model, price, description, and preview.


Tutorial-searchexample.png


Start from Example Project

You can get the source code of this article and import it to your IDE without starting from scratch. Please follow the README to run the project.

If you want to start a new project, please refer to ZK Installation Guide/Quick Start.

Declaring Domain Class

The following is the domain object that represents a car.

public class Car {
	private Integer id;
	private String model;
	private String make;
	private String preview;
	private String description;
	private Integer price;
	//omit getter and setter for brevity
}

We then define a service class to perform the business logic (search cars) shown below:

public interface CarService {

	/**
	 * Retrieve all cars in the catalog.
	 * @return all cars
	 */
	public List<Car> findAll();
	
	/**
	 * search cars according to keyword in  model and make.
	 * @param keyword for search
	 * @return list of car that matches the keyword
	 */
	public List<Car> search(String keyword);
}

In this example, we have defined a class, CarServeImpl, that implements the above interface. For simplicity, it uses a static list object as the data model. You can rewrite it so that it connects to a database in a real application. Its implementation details are not in the scope of this article, please refer to source code repository.

Building User Interface

UI is a good start to building an application as it helps you define the scope of your application. ZK provides hundreds of readily made UI components, so developers can rapidly build their desired user interface by combining and mix-matching these components without having to create a page from scratch.

In ZK, you can use ZK User Interface Markup Language (ZUML), an XML-formatted language, to describe UI. By ZK's convention, the files to describe the user interface with ZUML uses .zul as the name suffix. In zul files, one component is represented as an XML element (tag) and you can configure each component's style, behavior, and function by setting XML element's attributes. (check ZK Component Reference for details)

In this example application, first of all, we want to use a Window with the specified title and normal border as our application's frame.


As Window is the outermost component, it is called the root component. Window is a commonly used container because it makes your web application look like a desktop application. Besides, it can also enclose other components. All other components inside Window are called its child components and should be put in <window>'s body.

Extracted from search.zul

1 	<window title="Search" border="normal" width="600px">
2 		<!-- put child components inside a tag's body -->
3 	</window>
  • Line 1: Specifying title bar text with title and make <window> display a normal border with border . For width attribute, use CSS like syntax such as 800px or 60%.


Our example application's user interface is divided into 3 areas within the <window> (from top to bottom):

  1. search function
  2. car list
  3. car details.
Tutorial-ui-3areas.png


Search Area

ZK components are like building blocks, you can combine and mix-match existing components to construct your desired UI. To allow users to search, we need a text to prompt users for input, a place to enter keywords, and a button for triggering the search. We can use the following ZK components to fulfill this requirement:

Extracted from search.zul

1 Keyword:
2 <textbox id="keywordBox" />
3 <button id="searchButton" label="Search" iconSclass="z-icon-search" style="margin: 0 0 5px 5px"/>
  • Line 1~2: Specifying the id attribute for some components allows you to control them by referencing their id.
  • Line 3: You can use built-in Font Awesome icon at iconSclass. Please refer to LabelImageElement#IconSclass for details.

Car List Area

ZK provides several components to display a collection of data such as listbox, grid, and tree. In this example, we use a listbox to display a list of cars with 3 columns: Model, Make, and Price. Here we use listcell with static label to demonstrate structure of a listitem. Later, we'll talk about how to create listitem dynamically with a collection of data.

Extracted from search.zul

 1 <listbox id="carListbox" emptyMessage="No car found in the result" rows="5">
 2     <listhead>
 3         <listheader label="Model" />
 4         <listheader label="Make" />
 5         <listheader label="Price" width="20%"/>
 6     </listhead>
 7     <listitem>
 8         <listcell label="car model"></listcell>
 9         <listcell label="make"></listcell>
10         <listcell>$<label value="price" /></listcell>
11     </listitem>
12 </listbox>
  • Line 1: rows determines the max visible row. emptyMessage is used to show a message when listbox contains no items.
  • Line 2: The listbox is a container component, and you can add listhead to define a column.
  • Line 7: The listitem is used to display data, and the number of listcell in one listitem usually equals to the number of listheader.

Car Details Area

hlayout and vlayout are layout components which arrange their child components in horizontal and vertical order.

Extracted from search.zul

1 	<hlayout style="margin-top:20px" width="100%">
2 		<image id="previewImage" width="250px" />
3 		<vlayout hflex="1">
4 			<label id="modelLabel" />
5 			<label id="makeLabel" />
6 			<label id="priceLabel" />
7 			<label id="descriptionLabel" />
8 		</vlayout>
9 	</hlayout>
  • Line 1: the style attribute allows you to customize component's style with CSS syntax.

Handling UI Logic

The next step after building the UI is to make it respond to user interaction. The pattern we introduce here is to control ZK components directly by their API. We call this Model-View-Controller (MVC) design pattern. This pattern divides an application into 3 parts.

The Model consists of application data and business rules. CarService and other classes used by it represent this part in our example application.

The View indicates the user interface. The zul page which contains ZK components represents this part. A user's interaction with components triggers events to be sent to controllers.

The Controller plays the role of a coordinator between View and Model. It receives events from View to update Model and retrieves data from Model to change View's presentation.

The Flow to Handle a User Action

Tutorial-mvc.png
  1. When a user interacts with a component (e.g. click a button) on a ZUL, the user action triggers an event.
  2. This event is sent to the controller and invokes the corresponding event listener method.
  3. The event listener method usually contains business logic, accesses data, and the logic to manipulate ZK components.
  4. A component's state change is responded to a browser, and ZK client updates the corresponding UI.


Creating UI Controllers

Extending SelectorComposer

In ZK, the controller is responsible for controlling ZK components and listening to events triggered by user interaction. We can create such a controller class by simply extending SelectorComposer :

1 package tutorial;
2 
3 // omit import for brevity
4 
5 public class SearchController extends SelectorComposer<Component> {
6 
7 }

Apply a Controller to a UI Component

After a controller is created, we associate it with its corresponding UI component. Associating a controller with a component is just specifying a fully-qualified class name for the target component's apply attribute. The following code shows how to associate a controller with a <window>.

Extracted from searchMvc.zul

1 	<window title="Search" width="600px" border="normal"
2 	apply="tutorial.SearchController">
3 	<!-- omit other components for brevity -->
4 	</window>


After associating the controller with the window component, the controller can listen to events sent from UI and retrieve components which allows us to implement the application's feature. Let's start from the "search car": a user enters a keyword, clicks the "Search" button to trigger the search.

Steps to implement an application feature:

  1. Declare a method that listens to a component's event
  2. Control UI components to implement presentation and business logic in the listener method

Listening to User Actions

When we apply a controller to a component, every event triggered by this component (and its child components) is sent to the controller. If we register an event listener for the triggered event, ZK will invoke the listener.

Since a user clicks "Search" button to trigger the search function, we have to register a listener method, search(), to "Search" button's onClick event with the following annotation:

@Listen("[EVENT_NAME] = #[COMPONENT_ID]")

For complete selector syntax, please refer to SelectorComposer javadoc.

The final code looks like:

1 public class SearchController extends SelectorComposer<Component> {
2 
3 	@Listen("onClick = #searchButton")
4 	public void search(){
5 
6 	}
7 }
  • Line 3: searchButton is the button's id specified in the zul, and you can find it in the previous zul. For complete selector syntax, please refer to SelectorComposer javadoc.
  • Line 4: Event listener must be a public method.

Controlling UI Components

After establishing the relationship between an event and an event listener method, we can start to implement application logic with components. But firstly we need to retrieve/wire the UI component's object by annotating @Wire on controller's member variables. Because ZK instantiates a page's components object according to the zul, you should get ZK-created component objects instead of calling new Window() manually.

Steps to retrieve components:

  1. Declare a variable with target component type (e.g. Listbox, Label...)
  2. Name the variable as component's ID.
    Matching ID is the default rule to match a component for @Wire, and please refer to Wire Components in Developer's Reference to know other ways.
  3. Annotate the variable with @Wire.


Then ZK will "wire" a corresponding ZK component object to the variable we declared. After this has been done, we can then control and manipulate UI by accessing those annotated member variables.

1 public class SearchController extends SelectorComposer<Component> {
2 
3 	@Wire
4 	private Textbox keywordBox;
5 	@Wire
6 	private Listbox carListbox;
7 
8 	//other codes...
9 }
  • Line 5-6: In searchMvc.zul, there is a listbox whose id is carListbox. ZK will make the variable carListbox reference to the listbox object after components are created.


The search method performs the logic: call CarService to search with a keyword and set result list to Listbox.

You can get a component's state in a browser with its getter methods, getValue(), or change a component's state like making a Label invisible with setter, setVisible(false), to achieve some dynamic UI effect.

 1 public class SearchController extends SelectorComposer<Component> {
 2 	//omit codes to get components
 3 
 4 	@Listen("onClick = #searchButton")
 5 	public void search(){
 6 		String keyword = keywordBox.getValue();
 7 		List<Car> result = carService.search(keyword);
 8 		carListbox.setModel(new ListModelList<Car>(result));
 9 	}
10 }
  • Line 6: We can easily get what keyword a user inputs by keywordBox.getValue()
  • Line 8: Notice that setModel() only accepts a ListModel object, so we can use org.zkoss.zul.ListModelList to wrap search result list. There are other ListModel objects for different collection types, please refer to List Model in Developer's Reference. To change data item displayed in a Listbox, call carListbox.setModel(). The model of a component is the data the component holds and we can change the model to change the data rendering on the screen, please refer to Model-Driven Rendering

Displaying a Data Collection

We have successfully made clicking "Search" button to invoke its corresponding event listener, but we would still find that content of listbox doesn't show the search result correctly. That is because we haven't specified how to render data model on the listbox. Now, we will use a special tag, <template>, to control the rendering of each car. ZK will render each object in the data model according to components inside <template/>.

Steps to use <template>:

  1. Use <template> to enclose components that we want to create repeatedly.
  2. Set template's name attribute with model.
  3. Use implicit variable, each, to assign domain object's properties to component's attributes.

Please refer to ZK Developer's Reference/MVC/View/Template/Listbox Template for more details.

Extracted from searchMvc.zul

 1 <listbox id="carListbox" rows="3" emptyMessage="No car found in the result">
 2     <listhead>
 3         <listheader label="Model" />
 4         <listheader label="Make" />
 5         <listheader label="Price" width="20%"/>
 6     </listhead>
 7     <template name="model">
 8         <listitem>
 9             <listcell label="${each.model}"/>
10             <listcell label="${each.make}"/>
11             <listcell label="${('$'+=each.price)}"/>
12         </listitem>
13     </template>
14 </listbox>
  • Line 1: Specify rows to limit how many rows to display for the Listbox, so that you don't have to measure its height in pixel.
  • Line 7: The template tag should be put inside the listbox.
  • Line 8: The <listitem> in previous section is for static data, we should replace it with current code.
  • Line 9: The "each" is a variable that references to a domain object in the model list which is Car in our example application. We can use it to access domain object's property with EL, e.g. ${each.price}.
  • Line 11: Concatenate 2 strings with EL 3 syntax: (+=)

Implementing "View Car Details"

The previous sections describe the basic steps to implement a feature. Let's recap them by implementing "view car details":

First, declare a method to listen to onSelect event of Listbox with @Listen.

Second, use @Wire to get UI components like previewImage, modelLabel, priceLabel, and descriptionLabel and assign value to them with setter.

SearchController.java

 1 public class SearchController extends SelectorComposer<Component> {
 2 
 3 	@Wire
 4 	private Listbox carListbox;
 5 	@Wire
 6 	private Label modelLabel;
 7 	@Wire
 8 	private Label makeLabel;
 9 	@Wire
10 	private Label priceLabel;
11 	@Wire
12 	private Label descriptionLabel;
13 	@Wire
14 	private Image previewImage;
15 
16 	@Listen("onSelect = #carListbox")
17 	public void showDetail(){
18 		Car selected = carListbox.getSelectedItem().getValue();
19 		previewImage.setSrc(selected.getPreview());
20 		modelLabel.setValue(selected.getModel());
21 		makeLabel.setValue(selected.getMake());
22 		priceLabel.setValue(selected.getPrice().toString());
23 		descriptionLabel.setValue(selected.getDescription());
24 	}
25 	//omit other codes for brevity
26 }
  • Line 16: register an onSelect event listner on the Listbox
  • Line 18: get user-selected item.
  • Line 19~23: publish the selected car detail to the browser by setter methods.


Approach Comparison

Here is the architectural picture to demonstrate the interaction between Model, View, and Controller/ViewModel.

Tutorial-mvc.pngTutorial-mvvm.png

The main differences are that Controller changes to ViewModel and there is a binder in MVVM to synchronize data instead of a Controller.


MVC Advantages

  • very intuitive, easy to understand
  • control components in fine-grained

For those who use ZK for the first time or beginners, we suggest you using the MVC pattern. Because it's easy to use and debug.

MVVM Advantages

  • suitable for design-by-contract programming
  • loose coupling with View
  • better reusability
  • better testability
  • better for responsive design


Both approaches can achieve many things in common and have their own strength. But there are still some differences between them. Building an application with the MVC pattern is more intuitive because you directly control what you see. Its strength is that you have total control of components to create child components dynamically, control custom components, or do anything a component can do.

In the MVVM pattern, because ViewModel is loosely-coupled with View (it has no reference to components), one ViewModel may associate with multiple Views without modification. UI designers and programmers may work in parallel. If data and behavior do not change, a View's change doesn't cause ViewModel to be modified. In addition, as ViewModel is a POJO, it is easy to perform unit test on it without any special environment. That means ViewModel has better reusability, testability, and better resistance to View change.


To summarize, see the comparison table below:

MVC
MVVM
Coupling with View Loose with layout Loose
Coupling with Component Tight Loose
Coding in View Component ID Data binding expression
Controller Implementation  Extends ZK's composer  a POJO
UI Data Access Direct access Automatic
Backend Data Access Direct access Direct access
UI Updating Manipulate components    Automatic (@NotifyChange)   
Component Controlling Granularity Fine-grained Normal
Performance High Normal