Professional Documents
Culture Documents
Products
ZK
ZK Studio
ZK Spring
ZK Spreadsheet
ZK Pivottable
ZK Calendar
ZK JSP
ZATS
Demos
ZK
ZK Studio
ZK SpreadSheet
ZK Pivottable
ZK Calendar
ZK Web Mail
ZK Sandbox
Real World Apps
Downloads
ZK
ZK Studio
ZK Spring
ZK Spreadsheet
ZK Pivottable
ZK Calendar
ZK JSP
ZATS
Why ZK
Features
Top Reasons
Who's Using
Case Studies
Testimonials
Community
Forum
Blog
Contributors
Blogosphere
Small Talks
Request Features
Report Bugs
Documentation
ZK
ZK Studio
ZK Spring
ZK Spreadsheet
ZK Pivottable
ZK Calendar
ZK JSP
ZATS
Support
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
1/14
27/09/2012
Support Options
Partners
About Us
Search..
Custom Search
Wiki Search
Contents
1 Introduction
2 Tutorial Objective
3 Warm Up
3.1 Setup Eclipse
3.2 Install ZK in a Web Project
3.3 Run an Application
3.4 Import and Run Example Application
4 Declaring Domain Class
5 Building the User Interface
6 Automatic UI Controlling
6.1 Abstracting the View
6.2 Binding UI to ViewModel
6.3 Displaying Data Collection
6.4 Implementing View Details Functionality
7 Approach Comparison
8 References
Introduction
This tutorial is intended for software developers who have experience in writing Java programs. We will guide you through how to build a modern web application with ZK. The target application
simple car catalog application. In this article, we will present an approach which is classified as the Model-View-ViewModel (MVVM) design pattern. Using this approach, ZK can control com
and it separates the UI from its controller clearly. In addition, you can also choose to go with the MVC approach that is covered in another tutorial [1].
We also provide the complete source code with an Eclipse project zip file in Import and Run Example Application 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 name, price, description, and preview.
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
2/14
27/09/2012
Warm Up
This section guides you through how to setup a project and use ZK in Eclipse. If you want to know how to build the application with ZK first, please skip it and start from Declaring Domain Class
how to prepare an environment to build a ZK web application in including setting the IDE, installing ZK, and running an application in a server.
Setup Eclipse
After this has been done, Eclipse will use XML editor to open your zul file.
3/14
27/09/2012
If you prefer to use an application server that supports older (< 3.0) Servlet specification or JDK 1.5, you need to add more configuration on web.xml. Please refer to ZK Installation G
3. Copy and paste the following sample code into hello.zul and save.
hello.zul
1
2
3
Now, in Project Explorer view your project would look something like:
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
4/14
27/09/2012
If you cannot find Project Explorer view, select menu Window \ Show View \ Project Explorer to open it.
Run an Application
Before running a web application, we must create a server in Eclipse. Select Window \ Preferences to open Preferences window and select Server \ Runtime Environments from the left. Clic
environment.
Select Apache \ Tomcat v7.0 Server as it supports Servlet 3.0 and tick Create a new local server, then click Next.
If you use JDK 1.5, you could choose Tomcat v6.0 but you will need more configuration on web.xml. Please refer to ZK Installation Guide in References .
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
5/14
27/09/2012
If you have installed Tomcat 7 previously, simply provide the directory path. If you haven't, proceed with the following steps:
1. Click Download and Install and choose a folder.
Notice that the installation path must not contain non-ASCII characters.
Please wait and do not interrupt the installation before it completes to ensure that the installation has been done properly.
Eclipse will download and install Tomcat into the folder you have specified.
3. After the installation has been completed, click Finish
Now you should be able to see a new entry in Server rumtime environments.
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
6/14
27/09/2012
Right click on hello.zul and select Run As \ Run on Server to run this zul on an application server.
Choose an existing Tomcat 7. Yon can also tick Always use this server when running this project option to avoid choosing a server each time you run the application in the future. Click
start running.
After the server starts running, Eclipse will open a browser and connect to http://localhost:8080/hello.zul automatically . If you can see the following image, then your project is ready to use ZK.
You can come back and follow these steps to run your application during this tutorial
7/14
27/09/2012
2. In Eclipse, select File \ Import \ General \ Existing Projects into Workspace, choose Select archive file to import example application zip file as a project into your Eclipse.
3. Then follow the instructions from Run an Application to run it.
We then define a service class to perform the business logic (search cars) shown below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* search cars according to keyword in name and company.
* @param keyword for search
* @return list of car that match the keyword
*/
public List<Car> search(String keyword);
In this example, we have defined a class - CarServeImplthat 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
application. Implementation details are not in the scope of this article, please refer to References section.[4]
UI Design 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 thei
combining and mix matching these components without having to create them from scratch.
In ZK, you can use ZK User Interface Markup Language (ZUML) [5], an XML-formatted language, to describe UI. By ZK's convention, the files to describe user interface with ZUML uses
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.[6]
In the case of this example application, first of all, we want to design a window with specified title and normal border as our application's frame.
Extracted from search.zul
1
2
3
As window is the outermost component, it is called the root component. Window is a commonly used container because it is a basic display element of a desktop-like application while it can also
All other components inside window are called child components and should be put in window tag's body. We set window's title bar text with "title" attribute and make window display a norma
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 within the window, they are (from top to bottom) search function, car list, and car details.
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
8/14
27/09/2012
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 us
keywords, and a button for triggering the search. We can use the following ZK components to fulfill this requirement:
Extracted from search.zul
1
2
3
4
5
<hbox align="center">
Keyword:
<textbox id="keywordBox" />
<button id="searchButton" label="Search" image="/img/search.png" />
</hbox>
components horizontally and you can probably guess by now that the h represents horizontal. As these child components have different heights,
"center" so they are aligned neatly along their center line. Here we also specify an "id" attribute for some components which allows you to control them by referencing their id. You can also easily c
specifying the path for the "image" attribute.
Car List Area. ZK provides several components to display a collection of data such as listbox, grid, and tree. In this example, we have chosen to use a listbox to display a list of cars with 3 co
Price. We set the "height" attribute so the number of rows visible is limited with respect to the height specified; you can drag scroll-bar to see the rest of rows. The "emptyMessage" attribute is use
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
listheader. Here we use listcell with static label to demonstrate structure of a listitem, and we'll talk about how to create listitem dynamically with respect to each data object in the next chapter
Extracted from search.zul
1
2
3
4
5
6
7
8
9
10
11
12
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 informatio
attribute allows you to customize component's style with CSS syntax.
Extracted from search.zul
1
2
3
4
5
6
7
8
9
<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>
You can see the complete zul file through the link in the References section. [7]
Automatic UI Controlling
The approach we introduce here to control user interaction is to let ZK control UI components for you. This approach is classified to Model-View-ViewModel (MVVM) design pattern.
application into three parts.
The Model consists of application data and business rules. CarServiceand other classes used by it represent this part in our example application.
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
9/14
27/09/2012
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 ViewModel is responsible for exposing data from the Model to the View and providing required action requested from the View. The ViewModel is type of View abstraction which contain
But ViewModel should contain no reference to UI components. ZK framework handles communication and state synchronization between View and ViewModel.
Under this approach, we just prepare a ViewModel class with proper setter, getter and behavior methods, then assign data binding expression to a component's attributes in a ZUL. Ther
synchronize data between ViewModel and components and handle events automatically according to binding expressions. We don't need to control components by ourselves.
Here we use search function to explain how MVVM works in ZK. Assume that a user click "Search" button then listbox updates its content. The flow is as follows:
1.
2.
3.
4.
According to above analysis, the ViewModel should have 3 variables for above states and one method for the behavior. In ZK, creating a ViewModel is like creating a POJO, and it exposes its s
properties through setter and getter methods. The search method implements search logic with service class and updates the property "carList".
SearchViewModel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package tutorial;
import java.util.List;
import org.zkoss.bind.annotation.*;
public class SearchViewModel {
private String keyword;
private List<Car> carList;
private Car selectedCar;
//omit getter and setter
Annotation
In ZK MVVM, any behavior which can be requested by a View is a command in a ViewModel. We can bind a component's event to the command and ZK will invoke the method when bound
let ZK know which behavior (method) can be requested, you should apply an annotation @Commandon a method. We mark search()as a "command" with default command name, search, w
name. The command name is used in data binding expression we'll talk about in next section.
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
10/14
27/09/2012
In search(), we change a ViewModel's property: carList. Thus, we should tell ZK this change with @NotifyChangeso that ZK can reload the changed property for us after it invokes this me
For "search" command, it looks like:
SearchViewModel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package tutorial;
import java.util.List;
import org.zkoss.bind.annotation.*;
public class SearchViewModel {
//omit other codes
@Command
@NotifyChange("carList")
public void search(){
carList = carService.search(keyword);
}
Binding UI to ViewModel
Under MVVM, we build our UI as same as we would with the MVC approach, then we specify relationship between a ZUL and a ViewModel by writing data binding expression in component's
components for us.
To bind a component to a ViewModel, we should apply a composer called org.zkoss.bind.BindComposer. This composer processes data binding expressions and initializes the ViewModel cla
component to a ViewModel by setting its viewModel attribute with following syntax:
@id('ID') @init('FULL.QUALIFIED.CLASSNAME')
@id() is used
to set ViewModel's id to whatever we want like a variable name. We will use this id to reference ViewModel's properties (e.g. vm.carList) in a data binding expression.
We should provide full-qualified class name for @init()to initialize the ViewModel object.
Extracted from searchMvvm.zul
1
2
3
4
After binding the ViewModel to the component, all its child components can access the same ViewModel and its properties.
We can bind View to both ViewModel's properties and behavior with data binding expression. Let's see how to use data binding to achieve search function.
Since we have declared variables in ViewModel class for component's states in previous section, we can bind component's attributes to them. After binding a component's attribute to ViewMode
between attribute's value and a ViewModel's property for us automatically. We can specify which attribute is bound to which property by writing data binding expression as a component attrib
@bind(vm.aProperty)
Remember that vmis the id we have given it in @id()previously and now we use it to reference ViewModel object.
There are 2 states which relate to search function to be stored in the ViewModel upon previous analysis. First, we want to store value of textbox in ViewModel's keyword. We can then bind "va
vm.keywordwith @bind(vm.keyword). Second, we want to store the data model of a listbox in ViewModel's carList, so we should bind listbox's "model" to vm.carList.
Extracted from searchMvvm.zul
1
2
3
4
5
6
7
<hbox>
Keyword:
<textbox value="@bind(vm.keyword)" />
<button label="Search" image="/img/search.png"/>
</hbox>
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result">
<!-- omit other tags -->
We can only bind a component's event attribute (e.g. onClick) to ViewModel's behavior. After we bind an event to a ViewModel, each time a user triggers the event, ZK finds the bound comman
order to handle clicking on "Search" button, we have to bind button's onClick attribute to a command method with following syntax:
@command('COMMAND_NAME')
We should look for command name specified in our ViewModel's command method.
Extracted from searchMvvm.zul
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
11/14
27/09/2012
1
2
3
4
5
6
7
<hbox>
Name Keyword:
<textbox value="@bind(vm.keyword)" />
<button label="Search" image="/img/search.png" onClick="@command('search')" />
</hbox>
<listbox height="160px" model="@bind(vm.carList)" emptyMessage="No car found in the result">
<!-- omit other tags -->
After binding this "onClick" event, when a user clicks "Search" button, ZK will invoke search() and reload the property "carList" which is specified in @NotifyChange.
The way to display a collection of data with data binding is very similar to the way in MVC approach. we will use a special tag, <template> [10], to control the rendering of each item. The only d
data binding expression instead of EL.
Steps to use <template> :
1. Use <template>to enclose components that we want to create iteratively.
2. Set template's "name" attribute to "model". [11]
3. Use implicit variable, each, to assign domain object's properties to component's attributes.
Extracted from searchMvvm.zul
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1. We bind attribute selectedItemof listbox to the property vm.selectedCarto save selected domain object.
2. Because we want to show selected car's details, we bind value of label and src of image to selected car's properties which can be access by chaining dot notation like vm.selectedCar.n
3. Each time a user selects a listitem, ZK saves selected car to the ViewModel. Then ZK reloads selectedCar's properties to those bound attributes.
1
2
3
4
5
6
7
8
9
10
11
12
13
Approach Comparison
The interaction picture at left side is MVC, and the one at right side is MVVM. The main differences are that Controller changes to ViewModel and there is a binder to synchronize data instead o
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
12/14
27/09/2012
MVC
MVVM
In MVVM, 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 pro
parallel. If data and behavior do not change, a View's change doesn't cause modifying ViewModel. In addition, as ViewModel is a POJO, it is easy to perform unit test on it without any special en
ViewModel has better reusability, testabiliby, and better resistance against View change.
To summarize, a comparison table is illustrated below:
MVC
MVVM
Loose
Tight
Loose
Coding in View
Component ID
Controller Implementation
a POJO
UI Data Access
Direct access
Automatic
Direct access
Direct access
UI Updating
Manipulate components
Automatic(@NotifyChange)
Fine-grained
Normal
Performance
High
Normal
References
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
258
Follow us via :
ZK RSS
StumbleUpon
ZK LinkedIn Group
twitter @zkoss
facebook fan page
Log in / create account
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
13/14
27/09/2012
books.zkoss.org/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVVM
14/14