ZK Proficient in 30 Minutes"
Line 26: | Line 26: | ||
--> | --> | ||
− | The next step after | + | The next step after building the UI is to make it respond to users. The approach we introduce here is to '''control UI component directly by yourself'''. This approach can be classified to '''Model-View-Controller''' ('''MVC''') design pattern. <ref> [[ZK Developer's Reference/MVC| MVC in Developer's Reference]] </ref> This pattern divides an application into three parts. |
The '''Model''' consists of application data and business rules. <tt>CarService</tt> and other classes used by it represent this part in our example application. | The '''Model''' consists of application data and business rules. <tt>CarService</tt> and other classes used by it represent this part in our example application. | ||
Line 32: | Line 32: | ||
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 '''View''' means user interface. The zul page which contains ZK components represents this part. A user's interaction with components triggers events to be sent to controllers. | ||
− | The '''Controller''' plays | + | The '''Controller''' plays the role of a coordinator between View and Model. It receives events from View to update Model and retrieve data to change View's presentation. |
Line 49: | Line 49: | ||
In ZK, the controller is responsible for controlling ZK components and listening to events triggered by user interaction. | In ZK, the controller is responsible for controlling ZK components and listening to events triggered by user interaction. | ||
− | + | We have to implement a controller class for the UI component which we wish to reference and control. We can simply extend '''org.zkoss.zk.SelectorComposer''' : | |
<source lang="java"> | <source lang="java"> | ||
Line 62: | Line 62: | ||
− | After a controller is implemented, you should associate it to a component in a zul file, so that the controller can control the component including its child components. Associating a controller to a component is just specifying full-qualified class name in target component's '''apply''' attribute. The following code shows how to associate a controller to a ''window''. | + | <After a controller is implemented, you should associate it to a component in a zul file, so that the controller can control the component including its child components. {After a controller is declared, we associate it to its corresponding UI component.}> 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''. |
'''Extracted from searchMvc.zul''' | '''Extracted from searchMvc.zul''' | ||
Line 76: | Line 76: | ||
− | After | + | After associating the controller to the <zul?>, the controller can listen events sent from UI and retrieve components. Thus we can use above <2 abilities ?> to implement application's function. Let's start from the search function: a user enters a keyword, clicks the "Search" button to trigger the search. <So, we should write codes to response clicking "Search" button.> |
Steps to implement a function: | Steps to implement a function: | ||
Line 82: | Line 82: | ||
# Control UI components to implement presentation and business logic in the listener method | # Control UI components to implement presentation and business logic in the listener method | ||
− | == | + | == Listening to User Action == |
− | When we associate a controller to a component, every event triggered by this component (and its child components) is sent to the controller. If there is a method which we | + | When we associate a controller to a component, every event triggered by this component (and its child components) is sent to the controller. If there is a method which we assigned to listen to the triggered event, it will be invoked. |
As a user clicks "Search" button to trigger the search function, we have to listener to "Search" button's "onClick" event. | As a user clicks "Search" button to trigger the search function, we have to listener to "Search" button's "onClick" event. | ||
− | We declare a method, <tt> search()</tt>, and specify it to be invoked when " | + | We declare a method, <tt> search()</tt>, and specify it to be invoked when <"Search button" is clicked with the following annotation>: |
<tt> @Listen("[EVENT_NAME] = #[COMPONENT_ID]").</tt> | <tt> @Listen("[EVENT_NAME] = #[COMPONENT_ID]").</tt> | ||
− | Such method is called an event listener method. | + | <Such method is called an event listener method. {we also called this a Command method in SmallTalks and Developer Reference}> |
The final code looks like: | The final code looks like: | ||
Line 103: | Line 103: | ||
} | } | ||
</source> | </source> | ||
− | * Line 3: | + | * Line 3: <tt>"searchButton"</tt> is the button component's id, and you can find it in previous zul. There are other syntax which can be specified in @Listen's parameter <ref> [http://www.zkoss.org/javadoc/latest/zk/org/zkoss/zk/ui/select/SelectorComposer.html selector syntax]</ref> to describe a component. |
* Line 4: It must be a public method. | * Line 4: It must be a public method. | ||
Line 139: | Line 139: | ||
− | The search method performs simple logic: call car service class to search with keyword and set result list to ''listbox''. | + | The search method performs a simple logic: call car service class to search with keyword and set result list to ''listbox''. |
For a variable which references to a component, we can get component's attribute such as user's input with getter (<tt>getValue()</tt>) or change a component's status like making a ''label'' invisible with setter (<tt>setVisible(false)</tt>) to achieve some dynamic UI effect. Hence, we can easily get what keyword a user inputs by <tt> keywordBox.getValue() </tt> and change data item of ''listbox'' by <tt> carListbox.setModel() </tt>. The model of a component is the data the component holds and you can change the model to change the data rendering on the screen. | For a variable which references to a component, we can get component's attribute such as user's input with getter (<tt>getValue()</tt>) or change a component's status like making a ''label'' invisible with setter (<tt>setVisible(false)</tt>) to achieve some dynamic UI effect. Hence, we can easily get what keyword a user inputs by <tt> keywordBox.getValue() </tt> and change data item of ''listbox'' by <tt> carListbox.setModel() </tt>. The model of a component is the data the component holds and you can change the model to change the data rendering on the screen. | ||
Line 156: | Line 156: | ||
* Line 8: Notice that <tt>setModel() </tt> only accepts a <tt>ListModel</tt> object, so we can use '''org.zkoss.zul.ListModelList''' to wrap search result list. There are other <tt>ListModel</tt> objects for different collection types, please refer to References section. <ref> [[ZK Developer's Reference/MVC/Model/List Model| List Model in Developer's Reference]] </ref> | * Line 8: Notice that <tt>setModel() </tt> only accepts a <tt>ListModel</tt> object, so we can use '''org.zkoss.zul.ListModelList''' to wrap search result list. There are other <tt>ListModel</tt> objects for different collection types, please refer to References section. <ref> [[ZK Developer's Reference/MVC/Model/List Model| List Model in Developer's Reference]] </ref> | ||
− | == | + | ==Displaying a Data Collection == |
− | We have successfully made clicking "Search" button invoke event listener, but | + | We have successfully made clicking "Search" button <to invoke its corresponding event listener>, but we'll still find that content of ''listbox'' doesn't show search result correctly. That is because we <haven't specified> how to render data model on a ''listbox''. Now, we will use a special tag, <tt> <template> </tt><ref>[[ZK Developer's Reference/MVC/View/Template]]</ref>, to control the rendering of each item. ZK will render template tag's content <iteratively> for each object in the <data model>. |
− | Steps to use template: | + | Steps to use <tt> <template> </tt>: |
# Use '''<tt><template></tt>''' to enclose components that you want to create repeatedly. | # Use '''<tt><template></tt>''' to enclose components that you want to create repeatedly. | ||
# Set template's "name" attribute to "model". <ref> [[ZK Developer's Reference/MVC/View/Template/Listbox Template]]</ref> | # Set template's "name" attribute to "model". <ref> [[ZK Developer's Reference/MVC/View/Template/Listbox Template]]</ref> | ||
Line 190: | Line 190: | ||
== Implement View Details Function == | == 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 to "onSelect" event of ''listbox'' with <tt>@Listen</tt> | + | Previous sections describe the basic steps to implement a function with ZK. Let's recap them by implementing "view details" function. We declare a method to listen to "onSelect" event of ''listbox'' with <tt>@Listen</tt>, then use <tt>@Wire</tt> to get components including previewImage, nameLabel, priceLabel, and descriptionLabel and <assign value to them with setter>. |
<source lang="java"> | <source lang="java"> |
Revision as of 21:44, 13 August 2012
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 we are going to build is a simple car catalog application. You will also learn basic concepts of ZK during this tutorial.
You can take look at the [http:// target application's live demo] and download the complete source code with an Eclipse project zip file under Import and Run Example Application section.
Tutorial Objective
Our target application is a simple car catalog application. This application has two functions:
- Search cars.
- Enter a keyword in the input field, click Search and search results will be displayed in the car list below.
- 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.
The next chapter guides you 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 Domain Class.
Warm Up
To begin, we will start with 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
In this tutorial, Eclipse IDE 3.7 (indigo) for Java EE developer is used to demonstrate the building of the car catalog application. (Download Eclipse here, extract the downloaded zip file to a folder and execute eclipse.exe to run Eclipse.)
In order to edit ZK UI pages in Eclipse, add "zul" (ZK UI page's file extension name) as a content type of XML format following these steps below:
- Select Window \ Preferences to open Preferences window
- On the left, select General --> Content Types. On right, expand Text node in "Content types" box and select XML
- Click Add and type in the content type you wish to add which is *.zul in this case, then click OK
After this has been done, Eclipse will use XML editor to open your zul file.
Install ZK in a Web Project
Download ZK
Download the ZK CE first (file name would look like zk-bin-[version].zip) and extract it to a folder.
Create a Project
To build a web application, first, create a "Dynamic Web Project" in Eclipse:
- Select File \ New \ Dynamic Web Project
- Enter warmup in Project name and keep every thing else default.
- You can leave "Target runtime" as "none".
- Notice that we set Dynamic web module version to 3.0 because we want to use Servlet 3.0 to eliminate application configuration.
Install ZK JAR
To use ZK in your project, you have to copy ZK JAR files into your project's library folder.
Copy the JAR files from the following directory 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 supports older (< 3.0) Servlet specification or JDK 1.5, you need to add 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 if the installation has been successful or not.
In Eclipse,
- Select File \ New \ File (or File \ New \ Other \ File ) to add a new file, hello.zul, under WebContent.
- Click Source tab to modify source.
- Copy and paste the following sample code into hello.zul and save.
hello.zul
<window title="My First ZK Application" border="normal">
Hello World!
</window>
Now, in Project Explorer view your project would look something like:
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. Click Add to add a server runtime 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 .
If you have installed Tomcat 7 previously, simply provide the directory path. If you haven't, proceed with the following steps:
- Click Download and Install and choose a folder.
- Notice that the installation path must not contain non-ASCII characters.
- Accept the license agreement and wait.
- Eclipse will show an error message before installation completes, please ignore this message.
- 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.
- After the installation has been completed, click Finish
Now you should be able to see a new entry in Server rumtime environments.
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 Finish and wait for the server to 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
Import and Run Example Application
We have prepared an Eclipse project zip file that contains the complete source code, you can download and import it to your Eclipse without having to start from scratch.
To use example application, follow the steps below:
- Download example application project zip file.
- 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.
- Then follow the instructions from Run an Application to run it.
Declaring Domain Class
The following is the domain object that represents a car.
public class Car {
private Integer id;
private String name;
private String company;
private String preview;
private String description;
private Integer price;
//omit getter and setter for brevity
}
- Please refer to References section to see the complete code. [2]
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 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 - CarServeImpl that implements the above user 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. Implementation details are not in the scope of this article, please refer to References section.[3]
Building the User Interface
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 their desired user interface by combining and mix matching these components without having to create them from scratch.
In ZK, you can use ZK User Interface Markup Language (ZUML) [4], an XML-formatted language, to describe UI. By ZK's convention, the files to describe user interface with ZUML uses .zul as the name suffix. In zul files, one component can be represented as an XML element (tag) and you can configure each component's style, behavior, and function by setting XML element's attributes.[5]
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
<window title="Search" width="600px" border="normal">
<!-- put child components inside a tag's body -->
</window>
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 enclose other components. 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 normal border with "border" attribute. For "width" attribute, use CSS like syntax such as "800px" or "60%".
Basically, our example application's user interface is divided into 3 areas within the window, they are (from top to bottom) search function, car list, and car details.
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
<hbox align="center">
Keyword:
<textbox id="keywordBox" />
<button id="searchButton" label="Search" image="/img/search.png" />
</hbox>
hbox () is a layout component that arranges its child components horizontally and you can probably guess by now that the h represents horizontal. As these child components have different heights, we set the "align" attribute to "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 create an image button by specifying the path at "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 columns: Name, Company and 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 used to show a message when listbox contains no items. The listbox is a container component, and you can add listhead to define a column. The listitem is used to display data, and the number of listcell in one listitem should equal to the number of listheader. Here we use listcell with static value to demonstrate structure of a listitem, and we'll talk about how to create listitem upon dynamic data in next chapter.
Extracted from search.zul
<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
<listhead>
<listheader label="Name" />
<listheader label="Company" />
<listheader label="Price" width="20%"/>
</listhead>
<listitem>
<listcell value="product name"></listcell>
<listcell value="company"></listcell>
<listcell>$<label value="price" /></listcell>
</listitem>
</listbox>
Car Details Area. Like the hbox, vbox is also a layout component which arranges its child component in vertical order. By combing these 2 layout components, we can present more information on a screen. The "style" attribute allows you to customize component's style with CSS syntax.
Extracted from search.zul
<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 complete zul through the link in References section. [6]
Handling UI Logic
The next step after building the UI is to make it respond to users. The approach we introduce here is to control UI component directly by yourself. This approach can be classified to Model-View-Controller (MVC) design pattern. [7] This pattern divides an application into three parts.
The Model consists of application data and business rules. CarService and other classes used by it represent this part in our example application.
The View means user interface. The zul page which contains ZK components represents this part. A user's interaction with components triggers events to be sent to controllers.
The Controller plays the role of a coordinator between View and Model. It receives events from View to update Model and retrieve data to change View's presentation.
- 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 invokes corresponding event listener method.
- The event listener method usually executes business logic or accesses data, then manipulate ZK components.
- A change in component's states in an event listener is reflected in its corresponding UI.
Declaring UI Controllers
In ZK, the controller is responsible for controlling ZK components and listening to events triggered by user interaction.
We have to implement a controller class for the UI component which we wish to reference and control. We can simply extend org.zkoss.zk.SelectorComposer :
package tutorial;
// omit import for brevity
public class SearchController 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. {After a controller is declared, we associate it to its corresponding UI component.}> 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.
Extracted from searchMvc.zul
<window title="Search" width="600px" border="normal"
apply="tutorial.SearchController">
<!-- omit other components for brevity -->
</window>
See the complete zul in References.[8]
After associating the controller to the <zul?>, the controller can listen events sent from UI and retrieve components. Thus we can use above <2 abilities ?> to implement application's function. Let's start from the search function: a user enters a keyword, clicks the "Search" button to trigger the search. <So, we should write codes to response clicking "Search" button.>
Steps to implement a function:
- Declare a method which listens to a component's event
- Control UI components to implement presentation and business logic in the listener method
Listening to User Action
When we associate a controller to a component, every event triggered by this component (and its child components) is sent to the controller. If there is a method which we assigned to listen to the triggered event, it will be invoked. As a user clicks "Search" button to trigger the search function, we have to listener to "Search" button's "onClick" event. We declare a method, search(), and specify it to be invoked when <"Search button" is clicked with the following annotation>:
@Listen("[EVENT_NAME] = #[COMPONENT_ID]").
<Such method is called an event listener method. {we also called this a Command method in SmallTalks and Developer Reference}>
The final code looks like:
public class SearchController extends SelectorComposer<Component> {
@Listen("onClick = #searchButton")
public void search(){
}
}
- Line 3: "searchButton" is the button component's id, and you can find it in previous zul. There are other syntax which can be specified in @Listen's parameter [9] to describe a component.
- Line 4: It must be a public method.
Control Components
After establishing the relationship between an event and an event listener method, we can start to implement method's logic with components. But firstly we should retrieve the UI component's object by annotating @Wire on controller's member variables.
Steps to retrieve components:
- Declare a variable with target component type (e.g. Listbox, Label...)
- Name the variable as component's ID. [10]
- 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 SearchController extends SelectorComposer<Component> {
@Wire
private Textbox keywordBox;
@Wire
private Listbox carListbox;
//other codes...
}
- Line 5-6: In searchMvc.zul, there is a listbox whose id is carListbox. ZK will make the variable carListbox reference to the listbox object after components are created.
The search method performs a simple logic: call car service class to search with keyword and set result list to listbox.
For a variable which references to a component, we can get component's attribute such as user's input with getter (getValue()) or change a component's status like making a label invisible with setter (setVisible(false)) to achieve some dynamic UI effect. Hence, we can easily get what keyword a user inputs by keywordBox.getValue() and change data item of listbox by carListbox.setModel() . The model of a component is the data the component holds and you can change the model to change the data rendering on the screen.
public class SearchController extends SelectorComposer<Component> {
//omit codes to get components
@Listen("onClick = #searchButton")
public void search(){
String keyword = keywordBox.getValue();
List<Car> result = carService.search(keyword);
carListbox.setModel(new ListModelList<Car>(result));
}
}
- Line 8: Notice that setModel() only accepts a ListModel object, so we can use org.zkoss.zul.ListModelList to wrap search result list. There are other ListModel objects for different collection types, please refer to References section. [11]
Displaying a Data Collection
We have successfully made clicking "Search" button <to invoke its corresponding event listener>, but we'll still find that content of listbox doesn't show search result correctly. That is because we <haven't specified> how to render data model on a listbox. Now, we will use a special tag, <template> [12], to control the rendering of each item. ZK will render template tag's content <iteratively> for each object in the .
Steps to use <template> :
- Use <template> to enclose components that you want to create repeatedly.
- Set template's "name" attribute to "model". [13]
- Use implicit variable, each, to assign domain object's properties to component's attributes.
Extracted from searchMvc.zul
<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
<listhead>
<listheader label="Name" />
<listheader label="Company" />
<listheader label="Price" width="20%"/>
</listhead>
<template name="model">
<listitem>
<listcell label="${each.name}"></listcell>
<listcell label="${each.company}"></listcell>
<listcell>$<label value="${each.price}" /></listcell>
</listitem>
</template>
</listbox>
- Line 7: The template tag should be put inside the listbox .
- Line 8: The <listitem> in previous chapter's zul is for static data, you 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. You can use it to access domain object's property with EL, e.g. ${each.name}.
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 to "onSelect" event of listbox with @Listen, then use @Wire to get components including previewImage, nameLabel, priceLabel, and descriptionLabel and <assign value to them with setter>.
public class SearchController extends SelectorComposer<Component> {
@Wire
private Listbox carListbox;
@Wire
private Label nameLabel;
@Wire
private Label companyLabel;
@Wire
private Label priceLabel;
@Wire
private Label descriptionLabel;
@Wire
private Image previewImage;
@Listen("onSelect = #carListbox")
public void showDetail(){
Car selected = carListbox.getSelectedItem().getValue();
previewImage.setSrc(selected.getPreview());
nameLabel.setValue(selected.getName());
companyLabel.setValue(selected.getCompany());
priceLabel.setValue(selected.getPrice().toString());
descriptionLabel.setValue(selected.getDescription());
}
//omit other codes for brevity
}
For complete source code, please refer to References section [14]
References
- ↑ ZK Installation Guide \ Create and Run Your First ZK Application Manually
- ↑ Car.java
- ↑ CarService.java CarServiceImpl.java
- ↑ ZUML Reference
- ↑ ZK Component Reference
- ↑ search.zul
- ↑ MVC in Developer's Reference
- ↑ searchMvc.zul
- ↑ selector syntax
- ↑ In fact, matching ID is the default rule to match a component for @Wire, and please refer to Wire Components to know other ways.
- ↑ List Model in Developer's Reference
- ↑ ZK Developer's Reference/MVC/View/Template
- ↑ ZK Developer's Reference/MVC/View/Template/Listbox Template
- ↑ SearchController.java