Get ZK Up and Running with MVC"

From Documentation
(composer -> controller)
 
(253 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Template:UnderConstruction}}
 
 
 
= Introduction =
 
= Introduction =
 
 
This tutorial is intended for software developers who have experience in writing Java program with Eclipse. We will guide you how to build a modern web application with ZK. The target application we are going to build is a simple bookstore catalog application. You will also learn basic concepts of ZK during this tutorial.
 
 
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]] section. To run the application please refer to [[Run on Server]]
 
 
 
<!--
 
<!--
 
target readers
 
target readers
Line 15: Line 5:
 
-->
 
-->
  
= Installation =
 
  
== Prerequisite ==
+
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]].
  
We use Eclipse IDE 3.7 (indigo) for Java EE developer [[File:Eclipse-javaee.png]] ([http://www.eclipse.org/downloads/packages/release/indigo/sr2 Download Eclipse]) to demonstrate the whole instructions.  
+
<!--  
 +
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.
  
=== Create a Web Project ===
 
  
Open Eclipse.
 
# select '''File \ New \ Dynamic Web Project'''
 
# enter '''zktutorial''' in Project name and keep every thing else default.
 
  
[[File:Tutorial-newproject.png]]
+
{{Template:tutorial common chapters}}
  
== Download ==
+
= Handling UI Logic =
 +
<!--
 +
In this chapter, you'll learn:
  
[http://www.zkoss.org/download/zk Download the ZK CE ] (file name should be ''zk-bin-6.0.2.zip'') and extract it to a folder.
+
# How to handle a component's event
 
+
# How to control components in a controller
== Add ZK JAR to Your Project==
+
# How to use a template
 
 
To use ZK in your project, you have to copy ZK JAR into your project's library folder.
 
 
 
Copy JAR files under following list to '''zktutorial/WEB-INF/lib''':
 
* {YOUR_ZK_UNZIP_FOLDER}/dist/lib
 
* {YOUR_ZK_UNZIP_FOLDER}/dist/lib/ext
 
 
 
 
 
== Create a Simple Page ==
 
 
 
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.
 
 
 
 
 
'''hello.zul'''
 
<source lang="xml">
 
<window title="My First ZK Application" border="normal">
 
Hello World!
 
</window>
 
</source>
 
 
 
== Run on the Server ==
 
 
 
Right click on hello.zul, in context menu, select '''Run As / Run on Server''' to run this zul on an application server.
 
 
 
[[File:Tutorial-runonserver.png]]
 
 
 
 
 
 
 
If you have defined servers before, choose an existing server. If you don't, select '''Manually define a new server''' and select '''Tomcat v7.0 Server''' . Then click "Next".
 
 
 
[[File:Tutorial-newserver.png]]
 
 
 
 
 
If you have installed Tomcat before, just provide your path. If you don't, proceed the following step:
 
# click '''Download and Install''' button and choose a folder
 
# accept the license agreement, wait for a minute.
 
#: Eclipse will download and install Tomcat into the folder you specified. After installation is complete, the '''Finish''' button will become enabled.
 
# Click '''Finish''' button to wait for server starting.
 
 
 
[[File:Tutorial-downloadinstall.png]]
 
 
 
 
 
 
 
Eclipse opens an internal browser automatically and connects to http://localhost:8080/hello.zul. If you can see the following image, then your installation is success.
 
 
 
[[File:Tutorial-hello.png]]
 
 
 
 
 
If you prefer to use Tomcat 6, please refer to ZK Installation Guide. <ref> [[ZK Installation Guide/Quick Start/Create and Run Your First ZK Application Manually| Create and Run Your First ZK Application Manually]] </ref>
 
 
 
= Example Application =
 
 
 
 
 
Our target application is a simple bookstore catalog application. This application only has 2 main functions:
 
# Search books.
 
#: Enter a keyword in the textbox on the upper part of a window, click search button and it displays the search result in the book list below.
 
# View details.
 
#: Click any item of the book list, then the area below the book list shows the selected book's detail data including name, price, description, and cover preview.
 
 
 
 
 
[[File:tutorial-searchexample.png]]
 
 
 
<!--
 
We describe domain objects here, because this section is independent from MVC and MVVM sections and domain part is unchanged for these 2 design patterns.
 
 
-->
 
-->
  
 +
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.
  
The following is the domain object that represents a book.  
+
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.  
  
<source lang="java">
+
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.
  
public class Book {
+
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.
private Integer id;
 
private String name;
 
private String thumbnail;
 
private String description;
 
private Float price;
 
//omit getter and setter for brevity
 
}
 
</source>
 
* Please refer to References section to see the complete code. <ref> [http:// Book.java] </ref>
 
  
 +
== The Flow to Handle a User Action ==
 +
[[File:tutorial-mvc.png | center]]
  
Then we define a service class to perform the business logic (search books) as follows:
+
# 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.
  
<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>
 
  
* The implementation detail is not in this article's scope, please refer to References section.<ref> [http:// BookService.java] [http:// BookServiceImpl.java] </ref>
+
== Creating UI Controllers==
  
=Sketch User Interface =
+
===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] :
  
[[Image:photo_pencil.jpg|left|150px]] 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 own user interface by combining these components without creating from scratch.
+
<syntaxhighlight line lang="java">
 
 
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 use '''.zul''' as file name suffix. One XML element (tag) represents a component, and each component's style, behavior, and function can be configured by setting XML element's attributes.<ref> [[ZK Component Reference|ZK Component Reference]] </ref> For example, the following code is a ''window'' with specified title and normal border of our example application.
 
 
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
 
 
<window title="Search Product" width="800px" border="normal">
 
<!-- put child components inside a tag's body -->
 
</window>
 
</source>
 
 
 
We use a ''window'' as our application's frame. As it 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", "60%". The "style" attribute allows you to customize component's style with CSS syntax.
 
 
 
 
 
Basically, our example application's user interface is divided into 3 areas inside a ''window'', they are (from top to bottom) search function, book list, and book details area.
 
 
 
<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;">
 
book list
 
</div>
 
<div style="border-style:dashed;border-width:1px;width:80px;text-align:center;">
 
book details
 
</div>
 
 
 
 
 
'''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 place to enter keywords, a button for triggering search, and a text to tell user what they should input. We can use following zk components to fulfill this requirement:
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
 
 
<hbox align="center">
 
<label>Book Name Keyword:</label>
 
<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 three 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.
 
 
 
 
 
'''Book List Area.''' ZK provides several components to display a collections of data such as ''listbox'', ''grid'', and ''tree''. We use ''listbox'' to display a list of book with 2 columns: Name and Price. The "rows" attribute is used to control how many rows are visible and you can drag scroll-bar to see the rest of rows. 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'' corresponds to the number of ''listheader''.
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
<listbox id="productListbox" rows="5">
 
<listhead>
 
<listheader label="Name" />
 
<listheader label="Price" />
 
</listhead>
 
<listitem>
 
<listcell value="product name"></listcell>
 
<listcell>$<label value="price" /></listcell>
 
</listitem>
 
</listbox>
 
</source>
 
 
 
 
 
 
 
 
 
'''Book Details Area.''' Like the ''hbox'', ''vbox'' is 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.
 
 
 
'''Extracted from search.zul'''
 
<source lang="xml">
 
<hbox style="margin-top:20px">
 
<image id="thumbImage" width="250px" />
 
<vbox>
 
<label id="nameLabel" />
 
<label id="priceLabel" />
 
<label id="descriptionLabel"/>
 
</vbox>
 
</hbox>
 
</source>
 
 
 
 
 
You can see complete zul through the link in reference section. <ref> [http:// source code of search.zul] </ref>
 
 
 
= Control Components =
 
 
 
[[Image:tutorial-control.jpg|left|150px]]The next step after sketching the UI is to make UI response to users. In ZK, we have 2 approaches to design an application, the first approach we introduce here is to '''control ZK UI component (Java object) directly by yourself in a controller'''. 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 approach divides an application into three parts.
 
 
 
The '''Model''' consists of application data and business rules.<tt>BookService</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 '''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. ZK composer represents this part.
 
 
 
 
 
[[File:zktutorial-mvc-interaction.png]]
 
 
 
# When a user interacts with a component (e.g. click a button) on a ZUL, the user's action triggers an event.
 
#: This event is sent to ZK composer (controller) and invoke users-implemented event listener method.
 
# The event listener that is corresponding to the component is invoked.
 
# 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.
 
 
 
 
 
 
 
[[File:tutorial-target.png]]In this chapter, you'll learn:
 
 
 
<div style="background-color:#FF9334;border:solid;border-width:2px;border-radius:10px;">
 
# How to handle a component's event
 
# How to control components in a composer
 
# How to use template
 
</div>
 
 
 
<div style="padding-left:20px">
 
== UI Controller==
 
</div>
 
 
 
In ZK, the controller is responsible for controlling ZK components and listening events which are triggered by user interaction.
 
 
 
In order to control UI in ZK, you have to implement a controller class for a ZUL. You can simply extends <javadoc>org.zkoss.zk.SelectorComposer</javadoc> :
 
 
 
<source lang="java">
 
 
package tutorial;
 
package tutorial;
  
 
// omit import for brevity
 
// omit import for brevity
  
public class SearchProductController extends SelectorComposer<Component> {
+
public class SearchController extends SelectorComposer<Component> {
  
 
}
 
}
</source>
+
</syntaxhighlight>
 
 
 
 
After a composer is implemented, you should associate it to a component in a zul file, so that the composer can control the component including its child components. Associating a composer to a component is just specifying full-qualified class name in target component's '''apply''' attribute. The following code shows how to associate a composer to a ''window''.
 
  
<source lang="xml"  high='2'>
+
===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>.
  
<window title="Search Product" width="800px" border="normal"
+
'''Extracted from [https://github.com/zkoss/zkbooks/blob/master/gettingStarted/getZkUp/src/main/webapp/searchMvc.zul searchMvc.zul]'''
apply="tutorial.SearchProductController">
+
<syntaxhighlight lang="xml"  highlight='2' line>
 +
<window title="Search" width="600px" border="normal"
 +
apply="tutorial.SearchController">
 
<!-- omit other components for brevity -->
 
<!-- omit other components for brevity -->
 
</window>
 
</window>
  
</source>
+
</syntaxhighlight>
 
 
 
 
 
 
 
 
When we associate a composer to a component, every event triggered by this component (and its child components) is sent to the composer. If there is a event listener method that corresponds to the component's event, it will be invoked. When a user interact with a component, ZK '''sends events automatically upon user's actions'''. For example, click a ''button'' issues an "onClick" event, select an item in a ''listbox'' issues an "onSelect" event. You don't need to worry about events generating.
 
  
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.
 
  
[[File:Icon-steps.png]]What you should do to handle an user's action:
+
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.  
# Declare a public method and specify which component's event this method listens
 
#: Make the method listen "Search" button's "onClick" event.
 
# Control UI components to implement presentation logic
 
#: Get the keyword value and pass to <tt> BookService</tt> to search for result.
 
  
 +
Steps to implement an application feature:
 +
# Declare a method that listens to a component's event
 +
# Control UI components to implement presentation and business logic in the listener method
  
<div style="padding-left:20px">
+
== Listening to User Actions ==
  
== 1. Declare Event Listener ==
+
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.
</div>
 
  
 +
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:
  
We declare a method, <tt> search() </tt>, to be invoked when '''"Search" button''' is '''clicked''', so we can specify the relationship with syntax:
+
<code> @Listen("[EVENT_NAME] = #[COMPONENT_ID]")</code>
  
<tt> @Listen("[EVENT_NAME] = #[COMPONENT_ID]").</tt>
+
For complete selector syntax, please refer to [http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/select/SelectorComposer.html SelectorComposer javadoc].
  
 
The final code looks like:  
 
The final code looks like:  
  
<source lang="java" high="3">
+
<syntaxhighlight lang="java" highlight="3" line>
public class SearchProductController extends SelectorComposer<Component> {
+
public class SearchController extends SelectorComposer<Component> {
  
 
@Listen("onClick = #searchButton")
 
@Listen("onClick = #searchButton")
Line 318: Line 98:
 
}
 
}
 
}
 
}
</source>
+
</syntaxhighlight>
* Line 3: There are other syntax to specify @Listen's parameter. <ref> selector syntax</ref>
+
* 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].
* Line 4: It must be a public method.
+
* Line 4: Event listener must be a public method.
  
<div style="padding-left:20px">
+
== Controlling UI Components ==
  
==2. Control ZK Component ==
+
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.
 +
 
 +
<!--
 +
<div style="float:left;width:80px">
 +
[[File:Icon-steps.png]]
 
</div>
 
</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>.
  
One of <tt>SelectorComposer</tt>'s features is allowing you to retrieve the UI component's object by annotating '''<tt>@Wire</tt>''' on controller's member variables.
 
  
[[File:Icon-steps.png]]Steps:
+
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.
# Declare a variable with corresponding component type (e.g. <tt>Listbox</tt>, <tt> Label</tt>...)
 
# Variable's name is the same 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>
 
# Annotate the variable with <tt>@Wire</tt>.
 
  
Then <tt>SelectorComposer</tt> 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.
+
<syntaxhighlight line lang="java" highlight="3,4,5,6">
  
<source lang="java" high="3,4">
+
public class SearchController extends SelectorComposer<Component> {
 
 
public class SearchProductController extends SelectorComposer<Component> {
 
  
 
@Wire
 
@Wire
private Listbox productListbox;
+
private Textbox keywordBox;
 +
@Wire
 +
private Listbox carListbox;
  
 
//other codes...
 
//other codes...
 
}
 
}
</source>
+
</syntaxhighlight>
* In mentioned search.zul, there is a ''listbox'' whose id is "productListbox". SelectorComposer will make productListbox 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 <code>carListbox</code> reference to the ''listbox'' object after components are created.
  
  
The search method performs simple logic: call book service class to search with keyword and set result list to ''listbox''.
+
The search method performs the logic: call <code>CarService</code> to search with a keyword and set result list to <code>Listbox</code>.
For a variable which references to a component, we can get data from zul such as user's input, or a button's visibility with getter (e.g. getValue()) or change it status like making a ''label'' red with setter to achieve some dynamic UI effect. Hence, we can easily get what keyword a users input by <tt> keywordBox.getValue() </tt> and change data item of ''listbox'' by <tt> productListbox.setModel() </tt>.  
 
  
<source lang="java" high="8">
+
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.
public class SearchProductController extends SelectorComposer<Component> {
+
 
 +
<syntaxhighlight line lang="java" highlight="8">
 +
public class SearchController extends SelectorComposer<Component> {
 
//omit codes to get components
 
//omit codes to get components
  
Line 359: Line 146:
 
public void search(){
 
public void search(){
 
String keyword = keywordBox.getValue();
 
String keyword = keywordBox.getValue();
List<Book> result = bookService.search(keyword);
+
List<Car> result = carService.search(keyword);
productListbox.setModel(new ListModelList<Book>(result));
+
carListbox.setModel(new ListModelList<Car>(result));
 
}
 
}
 
}
 
}
</source>
+
</syntaxhighlight>
* Line 8: Notice that <tt>setModel() </tt> only accepts <tt>ListModel</tt> object, because ''listbox'' needs to control selection. We can use <javadoc>org.zkoss.zul.ListModelList</javadoc> to wrap search result list. There are other <tt>ListModel</tt> object for different collection types, please refer to reference section. <ref> [[ZK Developer's Reference/MVC/Model/List Model| List Model in Developer's Reference]] </ref>
+
* 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]]
  
<div style="padding-left:20px">
+
==Displaying a Data Collection ==
  
== Use Template ==
 
</div>
 
  
We have successfully made "Search" button invoke event listener, but you still find that content of ''listbox'' doesn't show search result. That is because we don't specify how to render data model of ''listbox''. Now, we will use a special tag, <tt> <template> </tt> to control the rendering of each item. ZK will render template tag's content repeatedly for each object in model of ''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, [[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>.
  
[[File:Icon-steps.png]]Steps:
+
Steps to use <code><template></code>:
# Use '''<tt><template></tt>''' to enclose components that you want to render repeatedly.
+
# Use <code><template></code> to enclose components that we want to create repeatedly.
# Set template's '''name''' attribute to '''"model"'''.
+
# Set template's <code>name</code> attribute with <code>model</code>.
# Use implicit variable '''each''' to assign domain object's properties to component's attributes.
+
# Use implicit variable, <code>each</code>, to assign domain object's properties to component's attributes.
#: The "each" is a variable that references to a domain object in the model list, you can use it to access domain object's property with EL, e.g. ${each.name}
 
  
 +
Please refer to [[ZK Developer's Reference/MVC/View/Template/Listbox Template]] for more details.
  
<source lang="xml" high="6,7,8,9,10,11">
+
'''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>
  
<listbox id="productListbox" rows="5">
+
== Implementing "View Car Details" ==
<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>
 
</source>
 
* Line 5:  The template tag's "name" attribute should be model and be declared inside the ''listbox''.
 
* Line 8: The implicit variable '''${each}" represents an object of the model which is <tt> Book</tt> in our example application.
 
  
 +
The previous sections describe the basic steps to implement a feature. Let's recap them by implementing "view car details":
  
<div style="padding-left:20px">
+
First, declare a method to listen to <code>onSelect</code> event of <code>Listbox</code> with <code>@Listen</code>.
== View Details Function ==
 
</div>
 
  
The steps to implement view details function is similar to search. We use <tt>@Wire</tt> to get components including thumbImage, nameLabel, priceLabel, and descriptionLabel and stuff data to them with setter in a method. Then declare that method to listen "onSelect" event of ''listbox'' with <tt>@Listen</tt>.  
+
Second, use <code>@Wire</code> to get UI components like previewImage, modelLabel, priceLabel, and descriptionLabel and assign value to them with setter.
  
<source lang="java">
+
[https://github.com/zkoss/zkbooks/blob/master/gettingStarted/getZkUp/src/main/java/tutorial/SearchController.java SearchController.java]
@Listen("onSelect = #productListbox")
+
<syntaxhighlight lang="java" line>
public void showDetail(){
 
Book selectedBook = productListbox.getSelectedItem().getValue();
 
thumbImage.setSrc(selectedBook.getThumbnail());
 
nameLabel.setValue(selectedBook.getName());
 
priceLabel.setValue("$"+selectedBook.getPrice());
 
descriptionLabel.setValue(selectedBook.getDescription());
 
 
}
 
</source>
 
  
 +
public class SearchController extends SelectorComposer<Component> {
  
For complete source code, please refer to Reference section <ref> [http:// SearchProductController.java] </ref>
+
@Wire
 +
private Listbox carListbox;
 +
@Wire
 +
private Label modelLabel;
 +
@Wire
 +
private Label makeLabel;
 +
@Wire
 +
private Label priceLabel;
 +
@Wire
 +
private Label descriptionLabel;
 +
@Wire
 +
private Image previewImage;
  
= Data Binding =
+
@Listen("onSelect = #carListbox")
 
+
public void showDetail(){
The second approach to handle user interaction is to '''let ZK control UI component for you'''. This approach is classified to '''Model-View-ViewModel''' ('''MVVM''') design pattern. <ref> [[ZK Developer's Reference/MVVM| MVVM in Developer's Reference]] </ref> This approach also divides an application into three parts. Only '''ViewModel''' is the different part from '''MVC'''. The ViewModel acts like ''a special Controller'' for the View which is responsible for exposing data from the Model to the View and for providing required action and logic for user requests from the View. The ViewModel is type of ''View abstraction'', which contains a View's state and behavior. But ''ViewModel should contain no reference to UI components'' and knows nothing about View's visual elements.
+
Car selected = carListbox.getSelectedItem().getValue();
 
+
previewImage.setSrc(selected.getPreview());
Under this approach, you just '''prepare a ViewModel class''' with proper setter, getter and data binding annotation. Then '''specify data binding expression on component's attributes'''. ZK's data binding mechanism will load and save data from ViewModel and handle events automatically according to your binding expression in a zul. You don't need to control components by yourself.
+
modelLabel.setValue(selected.getModel());
 
+
makeLabel.setValue(selected.getMake());
 
+
priceLabel.setValue(selected.getPrice().toString());
Here we use search scenario to explain how MVVM works in ZK. Assume that a user click "Search" button then ''listbox'' updates its content. The flow is as follows:
+
descriptionLabel.setValue(selected.getDescription());
 
 
[[Image:tutorial-mvvm.png|582px]]
 
 
 
 
 
# A user clicks "Search" button.
 
# A corresponding event is fired.
 
# The data binding mechanism finds the corresponding method ('''Command''') in the ViewModel and invokes it.
 
# The method accesses data from Model layer and updates some ViewModel's properties.
 
# ViewModel notify data binding mechanism that some properties have been changed.
 
# Per what properties have been changed, data binding mechanism loads data from the ViewModel.
 
# Data binding mechanism then updates the corresponding UI components to provide visual feedback to the user.
 
 
 
 
 
[[File:tutorial-target.png]]In this chapter, you'll learn:
 
 
 
<div style="background-color:#FF9334;border:solid;border-width:2px;border-radius:10px;">
 
# How to implement a ViewModel
 
# How to use data binding
 
# How to use command binding and change notification
 
</div>
 
 
 
==ViewModel==
 
 
 
 
 
In ZK, ViewModel can be simply a '''POJO''', and it should not contain any variable which references to UI components.  
 
 
 
[[File:Icon-steps.png]]Steps to associate a ViewModel to a zul:
 
# Implement a ViewModel class
 
# Set target component's <tt> apply</tt> and <tt>  viewModel</tt> attribute
 
 
 
 
 
 
 
Creating a ViewModel is like creating a POJO, and it exposes its properties like JavaBean through setter and getter methods.
 
 
 
<source lang="java">
 
package tutorial;
 
 
 
//omit import statements
 
 
 
public class SearchViewModel{
 
//declare properties, setter, and getter methods
 
 
 
private String keyword;
 
 
 
public void setKeyword(String keyword) {
 
this.keyword = keyword;
 
 
}
 
}
 +
//omit other codes for brevity
 
}
 
}
 
+
</syntaxhighlight>
</source>
+
* Line 16: register an <code>onSelect</code> event listner on the <code>Listbox</code>
 
+
* Line 18: get user-selected item.
 +
* Line 19~23: publish the selected car detail to the browser by setter methods.
  
  
We can bind ZK UI component to a ViewModel by setting a component's '''viewModel''' attribute, and that component becomes the '''Root View Component''' for the ViewModel. All child components of this Root View Component can acces the same ViewModel and its properties. To bind a ViewModel, we have to apply a composer called '''org.zkoss.bind.BindComposer''', it will create a binder for the ViewModel and instantiate the ViewModel's class. Then we use ZK Bind annotations to set ViewModel's id in <tt> @id </tt> and the ViewModel's full-qualified class name in <tt> @init </tt>.  The id is used to reference ViewModel's properties, e.g. vm.name, whilst the full-qualified class name is used to instantiate the ViewModel object itself.
 
  
<source lang="xml" high="2">
+
{{Template:tutorial Approach Comparison}}
<window title="Search Product" width="800px" border="normal"
 
apply="org.zkoss.bind.BindComposer" viewModel="@id('vm')@init('tutorial.SearchViewModel')">
 
<!-- omit other tags-->
 
</window>
 
</source>
 
 
 
 
 
 
 
 
 
When we associate a ViewModel to a component, we can bind attributes of this component (and its child components) to the ViewModel. When a user interact with components, ZK sends events automatically to the ViewModel like the case in MVC. ViewModel has its own way to specify event handlers.
 
 
 
Let's also 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.
 
 
 
== 1. Bind Properties to Component Attributes ==
 
 
 
The ViewModel class should contain data for components. You should provide getter method for loading data to a component and setter method for saving component's data back to Viewmodel. In our example, we declare <tt>keyword</tt> for ''text'' and <tt>bookList</tt> for ''listbox''.
 
 
 
<source lang="java">
 
public class SearchViewModel {
 
 
 
private String keyword;
 
private List<Book> bookList;
 
 
 
public void setKeyword(String keyword) {
 
this.keyword = keyword;
 
}
 
 
public List<Book> getBookList(){
 
return bookList;
 
}
 
}
 
</source>
 
 
 
Then we can bind "value" of ''textbox'' to <tt>vm.keyword</tt> with <tt>@save(vm.keyword)</tt>, because we want to save user input value into ViewModel. Remember that <tt>vm</tt> is the id we used to reference ViewModel and we give it in <tt> @id()</tt> in previous section. We use <tt>@load</tt> to load book list from ViewModel.
 
 
 
<source lang="xml" high="3,6">
 
 
 
<hbox>
 
<label>Book Name Keyword:</label>
 
<textbox value="@save(vm.keyword)" />
 
<button label="Search" image="/img/search.png" />
 
</hbox>
 
<listbox id="productListbox" rows="5" model="@load(vm.bookList)" >
 
<!-- omit other tags -->
 
 
 
</source>
 
 
 
== 2. User Actions as Commands ==
 
 
 
In ZK MVVM, we treat every event as a command to the ViewModel, and we write a '''Command method''' with '''<tt> @Command</tt>''' to handle this event. Thus, when a user action triggers an event, the ViewModel's corresponding command method is executed. The method may update properties value or perform business logic with service class.
 
 
 
[[File:Icon-steps.png]] The steps to bind an event to ViewModel's command method:
 
# Specify an event attribute with <tt>@command('commandName')</tt>
 
# Implement a method which has name as command name and annotate with <tt>@Command</tt>
 
# Notify properties change with <tt>@NotifyChange</tt>
 
 
 
 
 
 
 
In order to handle clicking on "Search" button, we specify button's onClick attribute. It's better to give a meaningful command name upon your context.
 
 
 
<source lang="xml" high="4">
 
<hbox>
 
<label>Book Name Keyword:</label>
 
<textbox value="@save(vm.keyword)" />
 
<button label="Search" image="/img/search.png" onClick="@command('search')" />
 
</hbox>
 
</source>
 
 
 
 
 
 
 
Then we implement a method to search with keyword and annotate it with <tt>@Command</tt> to complete the binding relationship. When a user clicks the "Search" button, ZK will invoke <tt>search()</tt>.
 
 
 
<source lang="java" high="3">
 
 
 
public class SearchViewModel {
 
 
@Command
 
public void search(){
 
bookList = bookService.search(keyword);
 
}
 
}
 
</source>
 
 
 
 
 
 
 
Now, we have handled button clicking but search result still doesn't update. Why? Why doesn't ZK load data from ViewModel? Because it doesn't know when or which data to reload. In MVVM approach, we can't stuff data into components directly. We have to notify ZK to load the data for us. After <tt>search() </tt> is invoked, we store search result in <tt>bookList</tt>. Hence, we should notify ZK to reload the property "bookList" as follows:
 
 
 
<source lang="java" high="3">
 
 
 
public class SearchViewModel {
 
 
 
@NotifyChange("bookList")
 
@Command
 
public void search(){
 
bookList = bookService.search(keyword);
 
}
 
</source>
 
* Line 3: If you want to notify multiple properties, use array format: <tt>@NotifyChange({"property01","property02"})</tt>
 
 
 
 
 
== View Details Function==
 
 
 
The steps to implement view details function are similar to search.
 
 
 
* We first declare a variable <tt>selectedBook</tt> to store selected item of ''listbox'' in the ViewModel and bind attribute <tt>selectedItem</tt> of ''listbox'' to the variable with <tt>@save(vm.selectedBook)</tt>.
 
* Because we want to show selected book's, we bind ''label'''s value and ''image'''s src to selected book's properties which can be access by dot notation like <tt>vm.selectedBook.name</tt>.
 
* Each time when a user selects a ''listitem'', ZK will set the data object to variable <tt>selectedBook</tt>. Then ZK will reload <tt>selectedBook</tt>'s properties to those bound attributes.
 
 
 
You may think why does ZK know to reload <tt>selectedBook</tt>'s properties when they are changed? Because ''setter method has default notification by default''', ZK will reload the target property changed by setter method automatically. You don't need to specify <tt>@NotifyChange</tt> to notify ZK the changed property itself.
 
 
 
 
 
<source lang="xml" high="2,6,8,9,10">
 
<listbox rows="5"
 
  model="@load(vm.bookList)" selectedItem="@save(vm.selectedBook)">
 
<!-- omit child components -->
 
</listbox>
 
<hbox style="margin-top:20px">
 
<image width="250px" src="@load(vm.selectedBook.thumbnail)" />
 
<vbox>
 
<label value="@load(vm.selectedBook.name)" />
 
<label value="@load(vm.selectedBook.price)" />
 
<label value="@load(vm.selectedBook.description)" />
 
</vbox>
 
</hbox>
 
</source>
 
 
 
= 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). ZATS Mimic enables you to test your composer '''without an application server''' and of course '''without a browser''' either. Through this library, testers can mimic user interactions to applications such as clicking or typing to''' verify composer's or ViewModel's (controller layer) data and logic'''. All you have to do is to '''write a regular unit test case''' and use Mimic's utility class to interact components on ZUL and then, run the test case.
 
 
 
No deploying to server, no rendering on browser, the unit test case can be executed in a very short period of time - this is very helpful for frequent unit testing during a agile development process.
 
 
 
We are going to demonstrate how to test our example application with ZATS Mimic.
 
 
 
== Setup ==
 
 
 
*  [http://www.zkoss.org/download/zats Download ZATS Mimic Binary]
 
*: Add all jar files under '''dist/lib''' and '''dist/lib/ext''' into your project's classpath. '''Note that please do not deploy these jars to your application server, they are for testing only'''.
 
* Add JUnit library to your project.
 
*: Right click the zktutorial project, Select '''Properties''' to enter project properties window. Select '''Java Build Path''', click ''' add Library''', select '''JUnit''', select '''JUnit 4''' in dropdown listbox, then click "Finish" button.
 
 
 
 
 
[[File:Tutorial-add-junit.png]]
 
 
 
 
 
== Write a Test Case ==
 
 
 
[[File:Icon-steps.png]]Steps to write a test case are as follows:
 
# Setup web application content path
 
# Create a client to connect to a ZUL
 
# Query a component
 
# Perform an operation on a component
 
# Verify result by checking a component’s property
 
# Tear down, stop server emulator
 
 
 
 
 
=== Fundamental Classes ===
 
 
 
Before showing source code, there are some basic classes you should know first.
 
 
 
; <javadoc directory="zats">org.zkoss.zats.mimic.Zats</javadoc>
 
:    It contains several utility methods to initialize and clean testing environment. By default, it starts server emulator '''with built-in web.xml and zk.xml ''' bundled in ZATS Mimic's jar.
 
; <javadoc directory="zats">org.zkoss.zats.mimic.DesktopAgent </javadoc>
 
:    Wraps ZK Desktop object, we usually call its <tt> query() </tt> or <tt> queryAll() </tt> to retrieve <tt> ComponentAgent </tt> with selector syntax.
 
:    For available selector syntax, please refer to <javadoc> org.zkoss.zk.ui.select.SelectorComposer </javadoc> or [[Small Talks/2011/January/Envisage ZK 6: An Annotation Based Composer For MVC]]
 
; <javadoc directory="zats">org.zkoss.zats.mimic.ComponentAgent </javadoc>
 
:    Mimics a ZK component and determines which operation you can perform on it. We can also get ZK component property's value from it.
 
: It also has <tt> query() </tt> which means to find targets among its child components.
 
; <javadoc directory="zats">org.zkoss.zats.mimic.operation.OperationAgent</javadoc> <tt>(ClickAgent, TypeAgent, SelectAgent...)</tt>
 
:    To mimic a user operation to a ZK component.
 
:    We name it "Agent" as it's not really the user operation itself, it's an agent to mimic user operation to a component.
 
 
 
 
 
=== Test Case Example ===
 
 
 
The steps we implement in test case to verify our example application are:
 
# mimic entering "java" in the textbox
 
# clicking "Search" button
 
# select each ''listitems'' in result list
 
# verify book's name in details area contains the keyword.
 
 
 
<source lang="java" high="5,10,14,,15,16,19,22,23,24">
 
 
 
public class TestSearch {
 
 
 
@BeforeClass
 
public static void init() {
 
Zats.init("./src/main/webapp"); // set web application root folder
 
}
 
 
 
@Test
 
public void test() {
 
DesktopAgent desktop = Zats.newClient().connect("/search.zul");
 
 
 
//enter keyword and click button
 
String keyword = "java";
 
ComponentAgent keywordBox = desktop.query("#keywordBox");
 
keywordBox.as(InputAgent.class).type(keyword);
 
desktop.query("#searchButton").as(ClickAgent.class).click();
 
 
//find all listitems
 
List<ComponentAgent> searchResult = desktop.queryAll("listitem");
 
for (ComponentAgent listitem : searchResult){
 
//select a listitem
 
listitem.as(SelectAgent.class).select();
 
String bookName = desktop.query("#nameLabel").as(Label.class).getValue();
 
Assert.assertTrue(bookName.toLowerCase().contains(keyword));
 
}
 
}
 
 
 
@AfterClass
 
public static void end() {
 
Zats.end();
 
}
 
 
 
@After
 
public void after() {
 
Zats.cleanup();
 
}
 
}
 
</source>
 
* Line 10: Create a client to visit our target zul.
 
* Line 14: Query in desktop to retrieve the ''textbox'' for keyword with its component's id.
 
* Line 15: You should convert <tt>ComponentAgent</tt> to <tt>InputAgent</tt> in order to type in a ''textbox''.
 
* Line 16: Get the button and click it in one statement.
 
* Line 19: The <tt>queryAll()</tt> retrieves all components that match selector syntax as a list.
 
* Line 22: To select a ''listitem", you have to get it first and convert it to <tt>SelectAgent</tt>.
 
* Line 23: You can also convert <tt>ComponentAgent</tt> to its native component type e.g. <tt>Label</tt> in order to get component's status.
 
* Line 24: We verify component's status with JUnit's assert methods.
 
 
 
= Download =
 
 
 
[Example application zip file]
 
 
 
= Reference =
 
 
 
<references/>
 
 
 
 
 
<!--
 
 
 
http://photopin.com
 
 
 
photo credit:
 
* binding image. [http://www.flickr.com/photos/ginapina/2908353017/ gina pina] via [http://photopin.com photo pin] [http://creativecommons.org/licenses/by/2.0/ cc]
 
 
 
-->
 
 
 
<!--
 
image source site:
 
 
 
http://www.freepixels.com/
 
 
 
http://icons.mysitemyway.com/
 
-->
 

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