Get ZK Up and Running with MVC"

From Documentation
(45 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Template:UnderConstruction}}
 
 
 
= Introduction =
 
= Introduction =
 
<!--
 
<!--
Line 8: Line 6:
  
  
This tutorial is intended for software developers who have experience in writing Java program. We will guide you how to build a modern web application with ZK. The target application we are going to build is a simple car catalog application. You will also learn basic concepts of ZK during this tutorial.
+
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 another tutorial. <ref> [[ZK Getting Started/Get ZK Up and Running with MVVM]]</ref>
  
You can take look at [http:// target application's live demo]. We also provide the complete source code with an Eclipse project zip file in [[#Download| Download]] section.
+
<!--
 +
take look at the [http:// target application's live demo] and
 +
-->
 +
You can download the complete source code with an Eclipse project zip file under [[#Start from Example Project| Start from Example Project]] section.
  
  
Line 17: Line 18:
 
{{Template:tutorial common chapters}}
 
{{Template:tutorial common chapters}}
  
 
+
= Handling UI Logic =
 
 
 
 
=Sketch User Interface =
 
 
 
Design UI is a good step to start building an application, since it helps you define the scope of your application. ZK provides hundreds of ready-made UI components. Developers can rapidly build their desired user interface by combining these components without creating from scratch.
 
 
 
In ZK, you can use ZK User Interface Markup Language (ZUML) <ref> [[ZUML Reference|ZUML Reference]] </ref>, an XML-formatted language, to describe user interface. In ZK default convention, the files to describe user interface with ZUML use '''.zul''' as file name suffix. In zul files, one component can be represented as an XML element (tag), and you can configure each component's style, behavior, and function by setting XML element's attributes.<ref> [[ZK Component Reference|ZK Component Reference]] </ref>
 
 
 
First of all, we use a ''window'' with specified title and normal border as our application's frame.
 
 
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
 
 
<window title="Search" width="600px" border="normal">
 
<!-- put child components inside a tag's body -->
 
</window>
 
</source>
 
 
 
As ''window'' is the outmost component, it's called the ''root component''. ''Window'' is a mostly common used container because it's a basic display element of a desktop-like application and it can also encloses other components. All other components inside the ''window'' should be put in window tag's body, and they are called ''child component''. We set ''window'''s title bar text with "title" attribute and make ''window'' display a normal border with "border" attribute. For "width" attribute, use CSS like syntax such as "800px" or "60%".
 
 
 
 
 
Basically, our example application's user interface is divided into 3 areas inside a ''window'', they are (from top to bottom) search function, car list, and car details area.
 
 
 
[[File:Tutorial-ui-3areas.png | 400px |center]]
 
 
 
 
 
'''Search Area.'''
 
ZK components are like building blocks, you can combine existing components to construct your desired user interface. To allow users to search, we need a text to tell user what they should input, a place to enter keywords, and a button for triggering search. We can use following ZK components to fulfill this requirement:
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
 
 
<hbox align="center">
 
Keyword:
 
<textbox id="keywordBox" />
 
<button id="searchButton" label="Search" image="/img/search.png" />
 
</hbox>
 
 
 
</source>
 
 
 
The ''hbox'' ("h" means horizontal) is a layout component and it can arrange its child components in horizontal order. Because these child components have different height, we use "align" attribute to arrange them for elegance. Here we specify "id" attribute for some components in order to control them, and we'll talk about the reason in next section. You can easily create an image button by specifying path at "image" attribute.
 
 
 
 
 
'''Car List Area.''' ZK provides several components to display a collection of data such as ''listbox'', ''grid'', and ''tree''. We use ''listbox'' to display a list of car with 3 columns: Name, Company and Price. We set "height" attribute to limit fixed number of visible row and you can drag scroll-bar to see the rest of rows. The "emptyMessage" attribute is used to show a message when ''listbox'' contains no items. The ''listbox'' is a container component, and you can add ''listhead'' to define a column. The ''listitem'' is used to display data, and the number of ''listcell'' in one ''listitem'' should equal to the number of ''listheader''. Here we use ''listcell'' with static value to demonstrate structure of a ''listitem'', and these will be replaced in next chapter.
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
 
<listhead>
 
<listheader label="Name" />
 
<listheader label="Company" />
 
<listheader label="Price" width="20%"/>
 
</listhead>
 
<listitem>
 
<listcell value="product name"></listcell>
 
<listcell value="company"></listcell>
 
<listcell>$<label value="price" /></listcell>
 
</listitem>
 
</listbox>
 
</source>
 
 
 
 
 
'''Car Details Area.''' Like the ''hbox'', ''vbox'' is also a layout component which arranges its child component in vertical order. By combing these 2 layout components, we can present more information on a screen.  The "style" attribute allows you to customize component's style with CSS syntax.
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
<hbox style="margin-top:20px">
 
<image id="previewImage" width="250px" />
 
<vbox>
 
<label id="nameLabel" />
 
<label id="companyLabel" />
 
<label id="priceLabel" />
 
<label id="descriptionLabel"/>
 
</vbox>
 
</hbox>
 
</source>
 
 
 
 
 
You can see complete zul through the link in References section. <ref> [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/WebContent/search.zul search.zul] </ref>
 
 
 
= Handle UI Logic =
 
 
<!--
 
<!--
 
In this chapter, you'll learn:
 
In this chapter, you'll learn:
Line 108: Line 27:
 
-->
 
-->
  
The next step after sketching the UI is to make UI response to users. The approach we introduce here is to '''control UI component directly by yourself'''. This approach can be classified to '''Model-View-Controller''' ('''MVC''') design pattern. <ref> [[ZK Developer's Reference/MVC| MVC in Developer's Reference]] </ref> This pattern divides an application into three parts.
+
The next step after building the UI is to make it respond to users. The approach we introduce here is to '''control UI component directly by yourself'''. This approach can be classified to '''Model-View-Controller''' ('''MVC''') design pattern. <ref> [[ZK Developer's Reference/MVC| MVC in Developer's Reference]] </ref> This pattern divides an application into three parts.
  
 
The '''Model''' consists of application data and business rules. <tt>CarService</tt> and other classes used by it represent this part in our example application.  
 
The '''Model''' consists of application data and business rules. <tt>CarService</tt> and other classes used by it represent this part in our example application.  
  
The '''View''' means user interface. The zul page which contains ZK components represents this part. An user's interaction with components triggers events to be sent to controllers.  
+
The '''View''' means 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 as a coordinator between View and Model. It receives events from View to update Model and retrieve data to change View's presentation.
+
The '''Controller''' plays the role of a coordinator between View and Model. It receives events from View to update Model and retrieve data from Model to change View's presentation.
  
  
Line 122: Line 41:
 
# This event is sent to the controller and invokes corresponding event listener method.
 
# This event is sent to the controller and invokes corresponding event listener method.
 
# The event listener method usually executes business logic or accesses data, then manipulate ZK components.
 
# The event listener method usually executes business logic or accesses data, then manipulate ZK components.
# Component's change made in event listeners reflects to UI change.
+
# A component's state change in an event listener is reflected in its corresponding UI.
  
  
  
== Declare an UI Controller==
+
== Declaring UI Controllers==
  
  
In ZK, the controller is responsible for controlling ZK components and listening events triggered by user interaction.
+
In ZK, the controller is responsible for controlling ZK components and listening to events triggered by user interaction. We can create a such controller class by simply extending '''org.zkoss.zk.SelectorComposer''' :
 
 
In order to control UI in ZK, you have to implement a controller class for a ZUL. You can simply extends '''org.zkoss.zk.SelectorComposer''' :
 
  
 
<source lang="java">
 
<source lang="java">
Line 144: Line 61:
  
  
After a controller is implemented, you should associate it to a component in a zul file, so that the controller can control the component including its child components. Associating a controller to a component is just specifying full-qualified class name in target component's '''apply''' attribute. The following code shows how to associate a controller to a ''window''.
+
After a controller is created, we associate it with its corresponding UI component. Associating a controller with a component is just specifying full-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'''
 
<source lang="xml"  high='2'>
 
<source lang="xml"  high='2'>
  
Line 154: Line 72:
  
 
</source>
 
</source>
 +
See the complete zul in References.<ref> [https://github.com/zkoss/zkbooks/blob/master/gettingStarted/getZkUp/src/main/webapp/searchMvc.zul searchMvc.zul] </ref>
  
  
After associate the controller to the zul, the controller can listen events sent from UI and retrieve components. Thus we can use above 2 abilities to implement application's function. Let's start from search function: an user enters a keyword, click the "Search" button to trigger the search. So, we should write codes to response clicking "Search" button.
+
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 application's function. Let's start from the search function: a user enters a keyword, clicks the "Search" button to trigger the search.  
  
 
Steps to implement a function:
 
Steps to implement a function:
Line 162: Line 81:
 
# Control UI components to implement presentation and business logic in the listener method
 
# Control UI components to implement presentation and business logic in the listener method
  
== Listen to User Action ==
+
== Listening to User Action ==
  
When we associate a controller to a component, every event triggered by this component (and its child components) is sent to the controller. If there is a method which we assign to listen to the triggered event, it will be invoked.
+
When we associate a controller with a component, every event triggered by this component (and its child components) is sent to the controller. If there is a method which we assigned to listen to the triggered event, it will be invoked.
As a user clicks "Search" button to trigger the search function, we have to listener to "Search" button's "onClick" event.
+
As a user clicks "Search" button to trigger the search function, we have to listen to "Search" button's "onClick" event.
We declare a method, <tt> search()</tt>, and specify it to be invoked when "clicking Search button" with following syntax:
+
We declare a method, <tt> search()</tt>, and specify it to be invoked when the "Search button" is clicked with the following annotation:
  
 
<tt> @Listen("[EVENT_NAME] = #[COMPONENT_ID]").</tt>
 
<tt> @Listen("[EVENT_NAME] = #[COMPONENT_ID]").</tt>
  
Such method is called an event listener method.
+
Such method serves as an event listener method.
  
 
The final code looks like:  
 
The final code looks like:  
Line 183: Line 102:
 
}
 
}
 
</source>
 
</source>
* Line 3: The <tt>searchButton</tt> is component's id, and you can find it in previous zul. There are other syntax which can be specified in @Listen's parameter <ref> [http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/select/SelectorComposer.html selector syntax]</ref> to describe a component.
+
* Line 3: <tt>"searchButton"</tt> is the button component's id, and you can find it in previous zul. There are other syntax which can be specified in @Listen's parameter <ref> [http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/select/SelectorComposer.html selector syntax]</ref> to describe a component.
 
* Line 4: It must be a public method.
 
* Line 4: It must be a public method.
  
== Control Components ==
+
== Controlling UI Components ==
  
  
Line 198: Line 117:
 
Steps to retrieve components:
 
Steps to retrieve components:
 
# Declare a variable with target component type (e.g. <tt>Listbox</tt>, <tt> Label</tt>...)
 
# Declare a variable with target component type (e.g. <tt>Listbox</tt>, <tt> Label</tt>...)
# Name the variable as component's ID. <ref> In fact, matching ID is the default rule to match a component for <tt>@Wire</tt>, and please refer to [[ZK Developer's Reference/MVC/Controller/Wire Components| Wire Components]] to know other ways. </ref>
+
# Name the variable as component's ID.  
 +
#: Matching ID is the default rule to match a component for <tt>@Wire</tt>, and please refer to ZK Developer's Reference <ref>[[ZK Developer's Reference/MVC/Controller/Wire Components| Wire Components in Developer's Reference]]</ref> to know other ways.  
 
# Annotate the variable with <tt>@Wire</tt>.
 
# Annotate the variable with <tt>@Wire</tt>.
  
  
Then ZK will "wire" a corresponding ZK component object to the variable you declared. After this has been done, you can then control and manipulate UI by accessing those annotated member variables.
+
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.
  
 
<source lang="java" high="3,4,5,6">
 
<source lang="java" high="3,4,5,6">
Line 211: Line 131:
 
private Textbox keywordBox;
 
private Textbox keywordBox;
 
@Wire
 
@Wire
private Listbox productListbox;
+
private Listbox carListbox;
  
 
//other codes...
 
//other codes...
 
}
 
}
 
</source>
 
</source>
* Line 5-6: In mentioned search.zul, there is a ''listbox'' whose id is productListbox. ZK will make the variable <tt>productListbox</tt> reference to the ''listbox'' object after components are created.
+
* Line 5-6: In searchMvc.zul, there is a ''listbox'' whose id is carListbox. ZK will make the variable <tt>carListbox</tt> reference to the ''listbox'' object after components are created.
  
  
The search method performs simple logic: call car service class to search with keyword and set result list to ''listbox''.
+
The search method performs a simple logic: call car service class to search with keyword and set result list to ''listbox''.
For a variable which references to a component, we can get component's attribute such as user's input with getter (<tt>getValue()</tt>) or change a component's status like making a ''label'' invisible with setter (<tt>setVisible(false)</tt>) to achieve some dynamic UI effect. Hence, we can easily get what keyword a user inputs by <tt> keywordBox.getValue() </tt> and change data item of ''listbox'' by <tt> productListbox.setModel() </tt>. The model of a component is the data the component holds and you can change the model to change the data rendering on the screen.
+
For a variable which references to a component, we can get component's attribute such as user's input with getter (<tt>getValue()</tt>) or change a component's status like making a ''label'' invisible with setter (<tt>setVisible(false)</tt>) to achieve some dynamic UI effect. Hence, we can easily get what keyword a user inputs by <tt> keywordBox.getValue() </tt> and change data item of ''listbox'' by <tt> carListbox.setModel() </tt>. 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.
  
 
<source lang="java" high="8">
 
<source lang="java" high="8">
Line 230: Line 150:
 
String keyword = keywordBox.getValue();
 
String keyword = keywordBox.getValue();
 
List<Car> result = carService.search(keyword);
 
List<Car> result = carService.search(keyword);
productListbox.setModel(new ListModelList<Car>(result));
+
carListbox.setModel(new ListModelList<Car>(result));
 
}
 
}
 
}
 
}
Line 236: Line 156:
 
* Line 8: Notice that <tt>setModel() </tt> only accepts a <tt>ListModel</tt> object, so we can use '''org.zkoss.zul.ListModelList''' to wrap search result list. There are other <tt>ListModel</tt> objects for different collection types, please refer to References section. <ref> [[ZK Developer's Reference/MVC/Model/List Model| List Model in Developer's Reference]] </ref>
 
* Line 8: Notice that <tt>setModel() </tt> only accepts a <tt>ListModel</tt> object, so we can use '''org.zkoss.zul.ListModelList''' to wrap search result list. There are other <tt>ListModel</tt> objects for different collection types, please refer to References section. <ref> [[ZK Developer's Reference/MVC/Model/List Model| List Model in Developer's Reference]] </ref>
  
==Display a Collection of Data ==
+
==Displaying a Data Collection ==
  
  
We have successfully made clicking "Search" button invoke event listener, but you still find that content of ''listbox'' doesn't show search result correctly. That is because we don't specify how to render data model of ''listbox''. Now, we will use a special tag, <tt> <template> </tt><ref>[[ZK Developer's Reference/MVC/View/Template]]</ref>, to control the rendering of each item. ZK will render template tag's content repeatedly for each object in model of a ''listbox''.
+
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, <tt> <template> </tt><ref>[[ZK Developer's Reference/MVC/View/Template]]</ref>, to control the rendering of each item. ZK will render each object in the data model according to components inside <tt><template/></tt>.
  
Steps to use template:
+
Steps to use <tt> <template> </tt>:
# Use '''<tt><template></tt>''' to enclose components that you want to create repeatedly.
+
# Use '''<tt><template></tt>''' to enclose components that we want to create repeatedly.
 
# Set template's "name" attribute to "model". <ref> [[ZK Developer's Reference/MVC/View/Template/Listbox Template]]</ref>
 
# Set template's "name" attribute to "model". <ref> [[ZK Developer's Reference/MVC/View/Template/Listbox Template]]</ref>
 
# Use implicit variable, '''each''', to assign domain object's properties to component's attributes.
 
# Use implicit variable, '''each''', to assign domain object's properties to component's attributes.
  
 +
'''Extracted from searchMvc.zul'''
 +
<source lang="xml" high="1,7,8,9,10,11,12,13">
  
<source lang="xml" high="7,8,9,10,11,12,13">
+
<listbox id="carListbox" rows="3" emptyMessage="No car found in the result">
 
 
<listbox id="productListbox" height="160px" emptyMessage="No car found in the result">
 
 
<listhead>
 
<listhead>
<listheader label="Name" />
+
<listheader label="Model" />
<listheader label="Company" />
+
<listheader label="Make" />
 
<listheader label="Price" width="20%"/>
 
<listheader label="Price" width="20%"/>
 
</listhead>
 
</listhead>
 
<template name="model">
 
<template name="model">
 
<listitem>
 
<listitem>
<listcell label="${each.name}"></listcell>
+
<listcell label="${each.model}"></listcell>
<listcell label="${each.company}"></listcell>
+
<listcell label="${each.make}"></listcell>
 
<listcell>$<label value="${each.price}" /></listcell>
 
<listcell>$<label value="${each.price}" /></listcell>
 
</listitem>
 
</listitem>
Line 264: Line 184:
 
</listbox>
 
</listbox>
 
</source>
 
</source>
* Line 7: The template tag should be put inside the ''listbox'' .  
+
* Line 1: Specify <tt>rows</tt> to limit how many rows to display for the Listbox, so that you don't have to measure its height in pixel.
* Line 8: The <listitem> in previous chapter's zul is for static data, you should replace it with current code.
+
* Line 7: The template tag should be put inside the listbox.  
* Line 9: The "each" is a variable that references to a domain object in the model list which is <tt> Car</tt> in our example application. You can use it to access domain object's property with EL, e.g. ${each.name}.
+
* Line 8: The <listitem> in previous chapter's zul 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 <tt> Car</tt> in our example application. We can use it to access domain object's property with EL, e.g. ${each.price}.
  
== Implement View Details Function ==
+
== Implementing the View Details Functionality ==
  
Previous sections describe the basic steps to implement a function with ZK. Let's recap them by implementing "view details" function. We declare a method to listen to "onSelect" event of ''listbox'' with <tt>@Listen</tt>.  Then use <tt>@Wire</tt> to get components including previewImage, nameLabel, priceLabel, and descriptionLabel and stuff data to them with setter.
+
Previous sections describe the basic steps to implement a function with ZK. Let's recap them by implementing "view details" function. We declare a method to listen to "onSelect" event of ''listbox'' with <tt>@Listen</tt>, then use <tt>@Wire</tt> to get components like previewImage, modelLabel, priceLabel, and descriptionLabel and assign value to them with setter.
  
 
<source lang="java">
 
<source lang="java">
Line 277: Line 198:
  
 
@Wire
 
@Wire
private Listbox productListbox;
+
private Listbox carListbox;
 
@Wire
 
@Wire
private Label nameLabel;
+
private Label modelLabel;
 
@Wire
 
@Wire
private Label companyLabel;
+
private Label makeLabel;
 
@Wire
 
@Wire
 
private Label priceLabel;
 
private Label priceLabel;
Line 289: Line 210:
 
private Image previewImage;
 
private Image previewImage;
  
@Listen("onSelect = #productListbox")
+
@Listen("onSelect = #carListbox")
 
public void showDetail(){
 
public void showDetail(){
Car selected = productListbox.getSelectedItem().getValue();
+
Car selected = carListbox.getSelectedItem().getValue();
 
previewImage.setSrc(selected.getPreview());
 
previewImage.setSrc(selected.getPreview());
nameLabel.setValue(selected.getName());
+
modelLabel.setValue(selected.getModel());
companyLabel.setValue(selected.getCompany());
+
makeLabel.setValue(selected.getMake());
 
priceLabel.setValue(selected.getPrice().toString());
 
priceLabel.setValue(selected.getPrice().toString());
 
descriptionLabel.setValue(selected.getDescription());
 
descriptionLabel.setValue(selected.getDescription());
Line 303: Line 224:
  
  
For complete source code, please refer to References section <ref> [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/src/tutorial/SearchController.java SearchController.java] </ref>
+
For complete source code, please refer to References section <ref> [https://github.com/zkoss/zkbooks/blob/master/gettingStarted/getZkUp/src/main/java/tutorial/SearchController.java SearchController.java] </ref>
  
= Download =
 
  
[http://zkbooks.googlecode.com/files/tutorial-20120803.zip Example application project zip file]
+
{{Template:tutorial Approach Comparison}}
  
Download the example application zip file. In Eclipse, select '''File \ Import \ Existing Projects into Workspace \ Select archive file''' to import example application zip file as a project to your Eclipse. Then follow the instructions in [[#Run an Application |Run an Application]] to run it.
 
  
 
= References =  
 
= References =  
  
 
<references/>
 
<references/>

Revision as of 07:01, 4 March 2020

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 another tutorial. [1]

You can download the complete source code with an Eclipse project zip file under 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 users. The approach we introduce here is to control UI component directly by yourself. This approach can be classified to Model-View-Controller (MVC) design pattern. [2] This pattern divides an application into three 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 means 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 retrieve data from Model to change View's presentation.


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


Declaring UI Controllers

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

package tutorial;

// omit import for brevity

public class SearchController extends SelectorComposer<Component> {

}


After a controller is created, we associate it with its corresponding UI component. Associating a controller with a component is just specifying full-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

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

See the complete zul in References.[3]


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 application's function. Let's start from the search function: a user enters a keyword, clicks the "Search" button to trigger the search.

Steps to implement a function:

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

Listening to User Action

When we associate a controller with a component, every event triggered by this component (and its child components) is sent to the controller. If there is a method which we assigned to listen to the triggered event, it will be invoked. As a user clicks "Search" button to trigger the search function, we have to listen to "Search" button's "onClick" event. We declare a method, search(), and specify it to be invoked when the "Search button" is clicked with the following annotation:

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

Such method serves as an event listener method.

The final code looks like:

public class SearchController extends SelectorComposer<Component> {

	@Listen("onClick = #searchButton")
	public void search(){

	}
}
  • Line 3: "searchButton" is the button component's id, and you can find it in previous zul. There are other syntax which can be specified in @Listen's parameter [4] to describe a component.
  • Line 4: It 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 method's logic with components. But firstly we should retrieve the UI component's object by annotating @Wire on controller's member variables.

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 ZK Developer's Reference [5] 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.

public class SearchController extends SelectorComposer<Component> {

	@Wire
	private Textbox keywordBox;
	@Wire
	private Listbox carListbox;

	//other codes...
}
  • 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 a simple logic: call car service class to search with keyword and set result list to listbox. For a variable which references to a component, we can get component's attribute such as user's input with getter (getValue()) or change a component's status like making a label invisible with setter (setVisible(false)) to achieve some dynamic UI effect. Hence, we can easily get what keyword a user inputs by keywordBox.getValue() and change data item of listbox by 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.

public class SearchController extends SelectorComposer<Component> {
	//omit codes to get components

	@Listen("onClick = #searchButton")
	public void search(){
		String keyword = keywordBox.getValue();
		List<Car> result = carService.search(keyword);
		carListbox.setModel(new ListModelList<Car>(result));
	}
}
  • 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 References section. [6]

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> [7], to control the rendering of each item. 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 to "model". [8]
  3. Use implicit variable, each, to assign domain object's properties to component's attributes.

Extracted from searchMvc.zul

		<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>
					<listcell label="${each.make}"></listcell>
					<listcell>$<label value="${each.price}" /></listcell>
				</listitem>
			</template>
		</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 chapter's zul 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}.

Implementing the View Details Functionality

Previous sections describe the basic steps to implement a function with ZK. Let's recap them by implementing "view details" function. We declare a method to listen to "onSelect" event of listbox with @Listen, then use @Wire to get components like previewImage, modelLabel, priceLabel, and descriptionLabel and assign value to them with setter.

public class SearchController extends SelectorComposer<Component> {

	@Wire
	private Listbox carListbox;
	@Wire
	private Label modelLabel;
	@Wire
	private Label makeLabel;
	@Wire
	private Label priceLabel;
	@Wire
	private Label descriptionLabel;
	@Wire
	private Image previewImage;

	@Listen("onSelect = #carListbox")
	public void showDetail(){
		Car selected = carListbox.getSelectedItem().getValue();
		previewImage.setSrc(selected.getPreview());
		modelLabel.setValue(selected.getModel());
		makeLabel.setValue(selected.getMake());
		priceLabel.setValue(selected.getPrice().toString());
		descriptionLabel.setValue(selected.getDescription());
	}
	//omit other codes for brevity
}


For complete source code, please refer to References section [9]


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


References