Get ZK Up and Running with MVC

From Documentation
Revision as of 02:32, 26 July 2012 by Hawk (talk | contribs)

WarningTriangle-32x32.png This page is under construction, so we cannot guarantee the accuracy of the content!

Introduction

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 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.



Warm Up

Tutorial-warmup.jpg

In this chapter, we'll guide you how to prepare an environment to build a web application with ZK including setting IDE, installing ZK, and running an application in a server.




Tutorial-double-arrow.png Setup Eclipse

We use Eclipse IDE 3.7 (indigo) for Java EE developer Eclipse-javaee.png (Download Eclipse) to demonstrate the whole instructions. Extract the downloaded zip file to a folder and execute eclipse.exe to open Eclipse.

In order to edit ZK UI page in Eclipse, you should add "zul" (It's ZK UI page's file extension name) as a content type of XML format as following steps:

  1. Select Window \ Preferences to enter Preferences window
  2. In left tree, select General / Content Types, on right hand side, expand Text node in "Content types" box, select XML
  3. Click Add button, type *.zul, and click OK button


Tutorial-add-contenttype.png


After this setup, when you double click a zul file, Eclipse will use XML editor to open it with syntax hightlight.

Tutorial-double-arrow.png Install ZK in a Web Project

Download ZK

Download the ZK CE (file name looks like zk-bin-[version].zip) and extract it to a folder.


Create a Project

To build a web application, you should create a "Dynamic Web Project" in Eclipse first:

  1. select File \ New \ Dynamic Web Project
  2. enter tutorial' in Project name and keep every thing else default.

Tutorial-newproject.png

  • You can leave "Target runtime" as "none".
  • Notice that we select Dynamic web module version to 3.0 because we want to use Servlet 3.0 to reduce application configuration.


Install ZK JAR

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 WebContent/WEB-INF/lib:

  • {YOUR_ZK_UNZIP_FOLDER}/dist/lib
  • {YOUR_ZK_UNZIP_FOLDER}/dist/lib/ext

If you prefer to use an application server that does not support Servlet 3.0 specification, you need more configuration on web.xml. Please refer to ZK Installation Guide. [1]


Create a Simple Page

After installation, you can create a simple zul to verify the installation works or not. In Eclipse,

  1. select File / New / File or File / New / Other / File to add a new file, hello.zul, under WebContent.
  2. Copy and paste the following sample code into hello.zul and save it.


hello.zul

 <window title="My First ZK Application" border="normal">
 	Hello World!
 </window>



After above steps, in Package Explorer view your project may look like:

Tutorial-project-structure.png

Tutorial-double-arrow.png Run an Application

Before running a web application, we must create a server in Eclipse. In Servers view, click new server wizard... or right click and select New \ Server. If you can't find Servers view tab, select menu Window \ Show View \ Servers to open it.

Tutorial-addserver.png


Select Manually define a new server and select Tomcat v7.0 Server . Then click "Next".

Tutorial-newserver.png


If you have installed Tomcat 7 before, just provide your path. If you don't, proceed the following step:

  1. click Download and Install button and choose a folder
  2. 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.
  3. Click Finish button to complete it.

Tutorial-downloadinstall.png



Right click on hello.zul, in context menu, select Run As / Run on Server to run this zul on an application server.

Tutorial-runonserver.png


Choose an existing Tomcat 7. Yon can also check Always use this server when running this project option to avoid choosing a server each time you run the application in the future. Click "Finish" button and wait for the server starts running.

Tutorial-choose-server.png


After server start running successfully, Eclipse opens an internal browser automatically and connects to http://localhost:8080/hello.zul. If you can see the following image, then your project is ready to use ZK.

Tutorial-hello.png


You can follow the steps of this section to run your application during reading this tutorial.

Example Application

Tutorial-double-arrow.png Use Case

Our target application is a simple bookstore catalog application. This application has 2 functions:

  1. 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.
  2. 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.


Tutorial-searchexample.png


Tutorial-double-arrow.png Domain Class

The following is the domain object that represents a book.

public class Book {
	private Integer id;
	private String name;
	private String thumbnail;
	private String description;
	private Float price;
	//omit getter and setter for brevity
}
  • Please refer to References section to see the complete code. [2]


Then we define a service class to perform the business logic (search books) as follows:

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);
}

We have a BookServeImpl that implements above interface. For simplicity it uses a static list object as the data model. You can replace it with connecting to a database in a real application. The implementation detail is not in this article's scope, please refer to References section.[3]



Sketch User Interface

Photo pencil.jpg

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.

In ZK, you can use ZK User Interface Markup Language (ZUML) [4], 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 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.[5]

First of all, we use a window with specified title and normal border as our application's frame.


Extracted from search.zul

	<window title="Search Product" width="800px" border="normal">
		<!-- put child components inside a tag's body -->
	</window>

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 windows 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%".


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.

Tutorial-ui-3areas.png


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

	 	<hbox align="center">
	 		Book Name Keyword:
	 		<textbox id="keywordBox" />
	 		<button id="searchButton" label="Search" image="/img/search.png" />
	 	</hbox>

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 collection of data such as listbox, grid, and tree. We use listbox to display a list of book with 2 columns: Name and Price. We set "height" attribute to limit fixed rows are visible 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 equals to the number of listheader.

Extracted from search.zul

	 	<listbox id="productListbox" height="160px" emptyMessage="No book found in the result">
			<listhead>
				<listheader label="Name" />
				<listheader label="Price" />
			</listhead>
			<listitem>
				<listcell value="product name"></listcell>
				<listcell>$<label value="price" /></listcell>
			</listitem>
		</listbox>



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. The "style" attribute allows you to customize component's style with CSS syntax.

Extracted from search.zul

		<hbox style="margin-top:20px">
			<image id="thumbImage" width="250px" />
			<vbox>
				<label id="nameLabel" />
				<label id="priceLabel" />
				<label id="descriptionLabel"/>
			</vbox>
		</hbox>


You can see complete zul through the link in reference section. [6]

Manipulate User Interface

Tutorial-control.jpg

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 UI component directly by yourself. This approach can be classified to Model-View-Controller (MVC) design pattern. [7] This approach divides an application into three parts.

The Model consists of application data and business rules.BookService 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.


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.
    This event is sent to the controller and invoke users-implemented event listener method.
  2. The event listener that is corresponding to the component is invoked.
  3. The event listener method usually executes business logic or accesses data, then manipulate ZK components.
  4. Component's change made in event listeners reflects to UI change.



Tutorial-double-arrow.png Declare an UI Controller

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 org.zkoss.zk.SelectorComposer :

package tutorial;

// omit import for brevity

public class SearchProductController extends SelectorComposer<Component> {

}


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.

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


After associate the controller to the zul, the controller can listen events sent by components 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.

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

Tutorial-double-arrow.png Handle 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 event listener method that corresponds to the component's event, it will be invoked. As a user clicks "Search" button to trigger the search function, we have to handle "Search" button's "onClick" event. We declare a method, search() , and specify it to be invoked when "Search" button is clicked with following selector syntax:

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

Such method is called an event listener.

The final code looks like:

public class SearchProductController extends SelectorComposer<Component> {

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

	}
}
  • Line 3: The "searchButton" is component's id, and you can find it in previous zul. There are other syntax which can be specified in @Listen's parameter. [8]
  • Line 4: It must be a public method.


Tutorial-double-arrow.png Control Components

After establishing the relationship between an event and an event listener, 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. [9]
  3. Annotate the variable with @Wire.


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.

public class SearchProductController extends SelectorComposer<Component> {

	@Wire
	private Listbox productListbox;

	//other codes...
}
  • In mentioned search.zul, there is a listbox whose id is "productListbox". ZK will make productListbox reference to the listbox object after components are created. There are other syntax for @Wire. [10]


The search method performs simple logic: call book 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 (e.g. getValue()) or change a component's 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 keywordBox.getValue() and change data item of listbox by productListbox.setModel() .

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

	@Listen("onClick = #searchButton")
	public void search(){
		String keyword = keywordBox.getValue();
		List<Book> result = bookService.search(keyword);
		productListbox.setModel(new ListModelList<Book>(result));
	}
}
  • Line 8: Notice that setModel() only accepts ListModel object, so we can use org.zkoss.zul.ListModelList to wrap search result list. There are other ListModel object for different collection types, please refer to reference section. [11]

Tutorial-double-arrow.png Display a Collection of Data

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, <template> , to control the rendering of each item. ZK will render template tag's content repeatedly for each object in model of a listbox.

Steps to use template:

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


		<listbox id="productListbox" height="160px" emptyMessage="No book found in the result">
			<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>
  • Line 6: The template tag's "name" attribute should be "model" and be declared inside the listbox.
  • Line 7: The <listitem> in previous chapter's zul is for static data, you should replace it with current example.
  • Line 8: The "each" is a variable that references to a domain object in the model list which is Book in our example application. You can use it to access domain object's property with EL, e.g. ${each.name}.

Tutorial-double-arrow.png Implement View Details Function

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 "onSelect" event of listbox with @Listen. Then use @Wire to get components including thumbImage, nameLabel, priceLabel, and descriptionLabel and stuff data to them with setter.

public class SearchProductController extends SelectorComposer<Component> {

	@Wire
	private Listbox productListbox;
	@Wire
	private Label nameLabel;
	@Wire
	private Label priceLabel;
	@Wire
	private Label descriptionLabel;
	@Wire
	private Image thumbImage;

	@Listen("onSelect = #productListbox")
	public void showDetail(){
		Book selectedBook = productListbox.getSelectedItem().getValue();
		thumbImage.setSrc(selectedBook.getThumbnail());
		nameLabel.setValue(selectedBook.getName());
		priceLabel.setValue(selectedBook.getPrice().toString());		
		descriptionLabel.setValue(selectedBook.getDescription());
		
	}
}


For complete source code, please refer to Reference section [12]



Bind User Interface

Tutorial-passive.jpg

The second approach to control user interaction is to let ZK control UI component for you. This approach is classified to Model-View-ViewModel (MVVM) design pattern. [13] This approach also divides an application into three parts. Only ViewModel is the different part from MVC. 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 contains a View's state and behavior. But ViewModel should contain no reference to UI components and knows nothing about View's visual elements. ZK framework handles communication and state synchronization between View and ViewModel.

Under this approach, you just prepare a ViewModel class with proper setter, getter and behavior methods. Then specify data binding expression on component's attributes in a ZUL. There is a binder in ZK which will transfer data between ViewModel and components and handle events automatically according to your binding expression. You don't need to control components by yourself.


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:

Tutorial-mvvm.png


  1. A user clicks "Search" button and a corresponding event is fired.
  2. ZK's binder invokes the corresponding command method in the ViewModel.
  3. The method accesses data from Model layer and updates some ViewModel's properties.
  4. ZK's binder reloads changed properties from the ViewModel to update component's states.


Tutorial-double-arrow.png Abstract the View

ViewModel is an abstraction of View. Therefore when we design a ViewModel, we should analysis UI's functions for what state it contains and what behavior it has.

The state:

  1. keyword from user input
  2. book list of search result
  3. selected book

The behavior:

  1. search


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 states like JavaBean's properties through setter and getter methods. The search method implements search logic with service class and updates property "bookList".

SearchViewModel.java

package tutorial;

import java.util.List;
import org.zkoss.bind.annotation.*;

public class SearchViewModel {

	private String keyword;
	private List<Book> bookList;
	private Book selectedBook;
	
	//omit getter and setter

	public void search(){
		bookList = bookService.search(keyword);
	}
}


Annotation

In ZK MVVM, any behavior which can be requested by a View is a command in a ViewModel. Then you can bind a component's event to the command and ZK will invoke the method when bound event is triggered. In order to let ZK knows which behavior (method) can be requested, we should apply an annotation @Command on a method. This annotation marks the method as a "command" with default command name, search, which is the same as method name. The command name is used in data binding expression we'll talk about in next section.


In above method, we change a ViewModel's property: bookList. Thus, we should tell ZK this change with @NotifyChange so that ZK can reload the changed property for us after it invokes this method.

For a "search" command, it looks like:

SearchViewModel.java

package tutorial;

import java.util.List;
import org.zkoss.bind.annotation.*;

public class SearchViewModel {

	//omit other codes

	@Command
	@NotifyChange("bookList")
	public void search(){
		bookList = bookService.search(keyword);
	}
}


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

Tutorial-double-arrow.png Bind UI to ViewModel

In MVVM approach, the way to sketch UI is the same as previous approach. Then you specify relationship between a ZUL and a ViewModel by writing data binding expression in component's attribute, and let ZK handles components for you.

To bind a component to a ViewModel, you should apply a composer called org.zkoss.bind.BindComposer. This composer processes data binding expressions and initializes the ViewModel's class. Then we can bind this 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 you want like a variable name. You will use this id to reference ViewModel's properties (e.g. vm.bookList) in a data binding expression.
  • You should provide full-qualified class name for init() to initialize the ViewModel object.


searchMvvm.zul

	<window title="Search Product" width="800px" border="normal" 
		apply="org.zkoss.bind.BindComposer" viewModel="@id('vm') @init('tutorial.SearchViewModel')">
	<!-- omit other tags-->
	</window>

After binding the ViewModel to the component, all its child components can access the same ViewModel and its properties.


Both ViewModel's properties and behavior can be bound to View with data binding expression. Let's see how to do it.

In previous section, we have declared variables in ViewModel class for component's states. By binding a component's attribute to ViewModel, ZK will synchronize data between components and ViewModel for us automatically. Now we are going to specify which attribute is bound to which property by writing data binding expression in a component attribute's value with syntax:

@bind(vm.myProperty)

  • Remember that vm is 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. Then we can bind "value" of textbox to vm.keyword with @bind(vm.keyword). Second, We expect to store the data model of a listbox in ViewModel's bookList, so we should bind listbox's "model" to vm.bookList.

searchMvvm.zul

		<hbox>
			Book Name Keyword:
			<textbox value="@bind(vm.keyword)" />
			<button label="Search" image="/img/search.png"/>
		</hbox>
		<listbox height="160px" model="@bind(vm.bookList)" emptyMessage="No book found in the result">
		<!-- omit other tags -->


Only event attribute (e.g. onClick) of a component can be bound to ViewModel's behavior. After you bind an event to a ViewModel, each time a user triggers the event, ZK finds bound command method and invokes it. In 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')

  • You should look for command name specified in your ViewModel's command method.

searchMvvm.zul

		<hbox>
			Book Name Keyword:
			<textbox value="@bind(vm.keyword)" />
			<button label="Search" image="/img/search.png" onClick="@command('search')" />
		</hbox>
		<listbox height="160px" model="@bind(vm.bookList)" emptyMessage="No book 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 "bookList" which is specified in @NotifyChange.

Tutorial-double-arrow.png Display a Collection of Data

The way to display a collection of data with data binding is very similar to the way in MVC approach. The only difference is you should use data binding expression instead of EL.

		<listbox height="160px" model="@bind(vm.bookList)" selectedItem="@bind(vm.selectedBook)" 
		emptyMessage="No book found in the result">
			<listhead>
				<listheader label="Name" />
				<listheader label="Price" />
			</listhead>
			<template name="model">
				<listitem>
					<listcell label="@bind(each.name)"></listcell>
					<listcell>$<label value="@bind(each.price)" />
					</listcell>
				</listitem>
			</template>
		</listbox>

Tutorial-double-arrow.png View Details Function

The steps to implement view details function are similar to previous section.

  1. We bind attribute selectedItem of listbox to the variable vm.selectedBook to save selected domain object.
  2. Because we want to show selected book's details, we bind value of label and src of image to selected book's properties which can be access by chaining dot notation like vm.selectedBook.name.
  3. Each time a user selects a listitem, ZK saves selected book to the ViewModel. Then ZK reloads selectedBook's properties to those bound attributes.


		<listbox height="160px" model="@bind(vm.bookList)" 
		selectedItem="@bind(vm.selectedBook)" emptyMessage="No book found in the result">
		<!-- omit child components -->
		</listbox>
		<hbox style="margin-top:20px">
			<image width="250px" src="@bind(vm.selectedBook.thumbnail)" />
			<vbox>
				<label value="@bind(vm.selectedBook.name)" />
				<label value="@bind(vm.selectedBook.price)" />
				<label value="@bind(vm.selectedBook.description)" />
			</vbox>
		</hbox>

Tutorial-double-arrow.pngApproach Comparison

The interaction picture at left side is MVC, and the one at right side is MVVM.

Tutorial-mvc.pngTutorial-mvvm.png


Both approaches can achieve many things in common, but there are still some differences between them. Each of two approaches has its strength. Building an application with MVC approach is more intuitive, because you controls what you see. Its strength is that you have total control of components, you can create child components dynamically, control custom components, or any thing a component can do.

In MVVM, because ViewModel is loosely-coupled with View (it has no reference to components), one ViewModel may associate with multiple Views without modification. If data and behavior do not change, a View's change doesn't cause modifying ViewModel. Besides, as ViewModel is a POJO, it is easy to perform unit test on it without any special environment. That means ViewModel has better reusability, testabiliby, and better resistance against View change.


To summarize, a comparison table is illustrated below:

MVVM
MVC
Coupling with View Loose Tight
Controller Implementation a POJO   a class that extends ZK's composer  
How to Update UI    Use ZK annotation to notify the binder    Manipulate components
Easy to Unit Test Controller(ViewModel) Yes No



Download

[Example application zip file]

Download the example application zip. 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 the Application to run it.



Reference

  1. Create and Run Your First ZK Application Manually
  2. [http:// Book.java]
  3. [http:// BookService.java] [http:// BookServiceImpl.java]
  4. ZUML Reference
  5. ZK Component Reference
  6. [http:// source code of search.zul]
  7. MVC in Developer's Reference
  8. selector syntax
  9. In fact, matching id is the default rule to match a component for @Wire, and please refer to Wire Components to know other ways
  10. syntax for @Wire
  11. List Model in Developer's Reference
  12. [http:// SearchProductController.java]
  13. MVVM in Developer's Reference
  14. [http:// SearchViewModel.java]

photo credit: