Difference between revisions of "Template:Tutorial common chapters"

From Documentation
 
(100 intermediate revisions by 8 users not shown)
Line 1: Line 1:
= Warm Up =
+
= 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 <b>Search</b> 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 model, price, description, and preview.
  
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.
 
  
 +
[[File:tutorial-searchexample.png| 400px | center]]
  
==Setup Eclipse ==
 
 
In this tutorial, Eclipse IDE 3.7 (indigo) for Java EE developer [[File:Eclipse-javaee.png]] is used to demonstrate the building of the car catalog application. ([http://www.eclipse.org/downloads/packages/release/indigo/sr2 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'''
 
 
[[File:Tutorial-add-contenttype.png| 400px | center]]
 
 
 
After this has been done, Eclipse will use XML editor to open your zul file.
 
 
== Install ZK in a Web Project==
 
 
'''Download ZK'''
 
 
[http://www.zkoss.org/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.
 
 
[[File:Tutorial-newproject.png | 400px | center]]
 
 
* 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
 
 
 
<div style="background-color:gold;border:solid;border-width:2px;border-radius:5px;padding-left:5px;padding-right:5px">
 
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. <ref> [[ZK Installation Guide/Quick Start/Create and Run Your First ZK Application Manually| ZK Installation Guide \ Create and Run Your First ZK Application Manually]] </ref>
 
</div>
 
 
 
'''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.
 
#: [[File:Tutorial-xmleditor.png| 400px | center]]
 
# Copy and paste the following sample code into hello.zul and save.
 
 
'''hello.zul'''
 
<source lang="xml">
 
<window title="My First ZK Application" border="normal">
 
Hello World!
 
</window>
 
</source>
 
 
 
 
 
Now, in '''Project Explorer''' view your project would look something like:
 
 
[[File:Tutorial-project-structure.png | 200px | center]]
 
 
If you cannot find '''Project Explorer''' view, select menu '''Window \ Show View \ Project Explorer''' to open it.
 
 
== Run an Application ==
 
<!--
 
將 new server 及 run on the server 分成兩個步驟,後面的章節可隨時依照run on the server的步驟執行範例程式
 
-->
 
 
 
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.
 
 
[[File:Tutorial-preference-server.png | 400px | center]]
 
 
 
Select '''Apache \ Tomcat v7.0 Server''' as it supports Servlet 3.0 and tick '''Create a new local server''', then click '''Next'''.
 
 
<div style="background-color:gold;border:solid;border-width:2px;border-radius:5px;padding-left:5px;padding-right:5px;">
 
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| References]] .
 
</div>
 
 
[[File:Tutorial-newserver.png | 400px | center]]
 
 
 
 
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.'''
 
#: [[File:Tutorial-installing-unknown.png | 400px | center]]
 
#: '''Please wait and do not interrupt the installation before it completes to ensure that the installation  has been done properly.'''
 
#: [[File:Tutorial-installing-progress.png | center]]
 
#: Eclipse will download and install Tomcat into the folder you have specified. 
 
# After the installation has been completed, click '''Finish'''
 
[[File:Tutorial-downloadinstall.png | 400px | center]]
 
 
Now you should be able to see a new entry in '''Server rumtime environments'''.
 
 
[[File:Tutorial-server-complete.png | 400px | center]]
 
 
 
 
Right click on hello.zul and select '''Run As \ Run on Server''' to run this zul on an application server.
 
 
[[File:Tutorial-runonserver.png | 400px | center]]
 
 
 
 
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.
 
 
[[File:Tutorial-choose-server.png | 400px | center]]
 
 
 
 
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.
 
 
[[File:Tutorial-hello.png | 400px | center]]
 
 
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:
 
# [http://zkbooks.googlecode.com/files/tutorial-20120807.zip 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 |Run an Application]] to run it.
 
 
= Example Application =
 
 
== Use Case==
 
Our target application is a simple car catalog application. This application has 2 functions:
 
# Search cars.
 
#: Enter a keyword in the input field, click search button and it displays the search result in the car list below.
 
# View details.
 
#: Click an item of the car list, then the area below the car list shows the selected car's details including name, price, description, and preview.
 
  
 +
= Start from Example Project =
  
[[File:tutorial-searchexample.png| 400px | center]]
+
You can get [https://github.com/zkoss-demo/gettingStarted/ 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]].
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.
 
-->
 
  
== Domain Class ==
+
= Declaring Domain Class =
  
 
The following is the domain object that represents a car.  
 
The following is the domain object that represents a car.  
Line 168: Line 24:
 
public class Car {
 
public class Car {
 
private Integer id;
 
private Integer id;
private String name;
+
private String model;
private String company;
+
private String make;
 
private String preview;
 
private String preview;
 
private String description;
 
private String description;
Line 176: Line 32:
 
}
 
}
 
</source>
 
</source>
* Please refer to References section to see the complete code. <ref> [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/src/tutorial/Car.java Car.java] </ref>
 
  
 
+
We then define a service class to perform the business logic (search cars) shown below:
Then we define a service class to perform the business logic (search cars) as follows:
 
  
 
<source lang="java">
 
<source lang="java">
Line 191: Line 45:
 
 
 
/**
 
/**
* search cars according to keyword in name and company.
+
* search cars according to keyword in model and make.
 
* @param keyword for search
 
* @param keyword for search
* @return list of car that match the keyword
+
* @return list of car that matches the keyword
 
*/
 
*/
 
public List<Car> search(String keyword);
 
public List<Car> search(String keyword);
Line 199: Line 53:
 
</source>
 
</source>
  
We have a <tt>CarServeImpl</tt> 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.<ref> [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/src/tutorial/CarService.java CarService.java] [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/src/tutorial/CarServiceImpl.java CarServiceImpl.java] </ref>
+
In this example, we have defined a class, <code>CarServeImpl</code>, 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 [[ZUML Reference|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|ZK Component Reference]] for details)
  
=Sketch User Interface =
+
In this example application, first of all, we want to use a <code>Window</code> with the specified title and normal border as our application's frame.
  
Design UI is a good step to start building an application, since it helps you define the scope of your application. ZK provides hundreds of ready-made UI components. Developers can rapidly build their desired user interface by combining these components without creating from scratch.
 
  
In ZK, you can use ZK User Interface Markup Language (ZUML) <ref> [[ZUML Reference|ZUML Reference]] </ref>, an XML-formatted language, to describe user interface. In ZK default convention, the files to describe user interface with ZUML use '''.zul''' as file name suffix. In zul files, one component can be represented as an XML element (tag), and you can configure each component's style, behavior, and function by setting XML element's attributes.<ref> [[ZK Component Reference|ZK Component Reference]] </ref>  
+
As <code>Window</code> is the outermost component, it is called the ''root component''. <code>Window</code> 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 <code>Window</code> are called its ''child components'' and should be put in <code><window></code>'s body.
  
First of all, we use a ''window'' with specified title and normal border as our application's frame.
+
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
 
+
<syntaxhighlight lang="XML" line>
 
+
<window title="Search" border="normal" width="600px">
'''Extracted from search.zul'''
 
<source lang="xml">
 
 
 
<window title="Search" width="600px" border="normal">
 
 
<!-- put child components inside a tag's body -->
 
<!-- put child components inside a tag's body -->
 
</window>
 
</window>
</source>
+
</syntaxhighlight>
 +
 
 +
* Line 1: Specifying title bar text with <code>title</code> and make <code><window></code> display a normal border with <code>border</code> . For <code>width</code> attribute, use CSS like syntax such as <code>800px</code> or <code>60%</code>.
  
As ''window'' is the outmost component, it's called the ''root component''. ''Window'' is a mostly common used container because it's a basic display element of a desktop-like application and it can also encloses other components. All other components inside the ''window'' should be put in window tag's body, and they are called ''child component''. We set ''window'''s title bar text with "title" attribute and make ''window'' display a normal border with "border" attribute. For "width" attribute, use CSS like syntax such as "800px" or "60%".
 
  
 +
Our example application's user interface is divided into 3 areas within the <code><window></code> (from top to bottom):
  
Basically, our example application's user interface is divided into 3 areas inside a ''window'', they are (from top to bottom) search function, car list, and car details area.
+
# search function
 +
# car list
 +
# car details.
  
 
[[File:Tutorial-ui-3areas.png | 400px |center]]
 
[[File:Tutorial-ui-3areas.png | 400px |center]]
  
  
'''Search Area.'''
+
== Search Area ==
ZK components are like building blocks, you can combine existing components to construct your desired user interface. To allow users to search, we need a text to tell user what they should input, a place to enter keywords, and a button for triggering search. We can use following ZK components to fulfill this requirement:
+
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'''
 
<source lang="xml">
 
 
 
<hbox align="center">
 
Keyword:
 
<textbox id="keywordBox" />
 
<button id="searchButton" label="Search" image="/img/search.png" />
 
</hbox>
 
 
 
</source>
 
 
 
The ''hbox'' ("h" means horizontal) is a layout component and it can arrange its child components in horizontal order. Because these child components have different height, we use "align" attribute to arrange them for elegance. Here we specify "id" attribute for some components in order to control them, and it allows you to use the id to identify a specific component. You can easily create an image button by specifying path at "image" attribute.
 
  
 +
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
 +
<syntaxhighlight lang="XML" line>
 +
Keyword:
 +
<textbox id="keywordBox" />
 +
<button id="searchButton" label="Search" iconSclass="z-icon-search" style="margin: 0 0 5px 5px"/>
 +
</syntaxhighlight>
  
'''Car List Area.''' ZK provides several components to display a collection of data such as ''listbox'', ''grid'', and ''tree''. We use ''listbox'' to display a list of car with 3 columns: Name, Company and Price. We set "height" attribute to limit fixed number of visible row and you can drag scroll-bar to see the rest of rows. The "emptyMessage" attribute is used to show a message when ''listbox'' contains no items. The ''listbox'' is a container component, and you can add ''listhead'' to define a column. The ''listitem'' is used to display data, and the number of ''listcell'' in one ''listitem'' should equal to the number of ''listheader''. Here we use ''listcell'' with static value to demonstrate structure of a ''listitem'', and we'll talk about how to create ''listitem'' upon dynamic data in next chapter.
+
* Line 1~2: Specifying the <code>id</code> attribute for some components allows you to control them by referencing their ''id''.  
 +
* Line 3: You can use built-in Font Awesome icon at <code>iconSclass</code>. Please refer to [[ZK_Component_Reference/Base_Components/LabelImageElement#IconSclass| LabelImageElement#IconSclass]] for details.
  
'''Extracted from search.zul'''
+
== Car List Area ==
<source lang="xml">
+
ZK provides several components to display a collection of data such as <code>listbox</code>, <code>grid</code>, and <code>tree</code>. In this example, we use a <code>listbox</code> to display a list of cars with 3 columns: Model, Make, and Price.  Here we use <code>listcell</code> with static label to demonstrate structure of a <code>listitem</code>. Later, we'll talk about how to create <code>listitem</code> dynamically with a collection of data.
<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
 
<listhead>
 
<listheader label="Name" />
 
<listheader label="Company" />
 
<listheader label="Price" width="20%"/>
 
</listhead>
 
<listitem>
 
<listcell value="product name"></listcell>
 
<listcell value="company"></listcell>
 
<listcell>$<label value="price" /></listcell>
 
</listitem>
 
</listbox>
 
</source>
 
  
 +
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
 +
<syntaxhighlight lang="XML" line>
 +
<listbox id="carListbox" emptyMessage="No car found in the result" rows="5">
 +
    <listhead>
 +
        <listheader label="Model" />
 +
        <listheader label="Make" />
 +
        <listheader label="Price" width="20%"/>
 +
    </listhead>
 +
    <listitem>
 +
        <listcell label="car model"></listcell>
 +
        <listcell label="make"></listcell>
 +
        <listcell>$<label value="price" /></listcell>
 +
    </listitem>
 +
</listbox>
 +
</syntaxhighlight>
 +
* Line 1: <code>rows</code> determines the max visible row. <code>emptyMessage</code> is used to show a message when <code>listbox</code> contains no items.
 +
* Line 2: The <code>listbox</code>  is a container component, and you can add <code>listhead</code> to define a column.
 +
* Line 7: The <code>listitem</code> is used to display data, and the number of <code>listcell</code> in one <code>listitem</code> usually equals to the number of <code>listheader</code>.
  
'''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.
+
== Car Details Area ==
 
+
<code>hlayout</code> and <code>vlayout</code> are layout components which arrange their child components in horizontal and vertical order.
'''Extracted from search.zul'''
 
<source lang="xml">
 
<hbox style="margin-top:20px">
 
<image id="previewImage" width="250px" />
 
<vbox>
 
<label id="nameLabel" />
 
<label id="companyLabel" />
 
<label id="priceLabel" />
 
<label id="descriptionLabel"/>
 
</vbox>
 
</hbox>
 
</source>
 
 
 
  
You can see complete zul through the link in References section. <ref> [http://code.google.com/p/zkbooks/source/browse/trunk/tutorial/WebContent/search.zul search.zul] </ref>
+
'''Extracted from [https://github.com/zkoss-demo/gettingStarted/blob/master/src/main/webapp/search.zul search.zul]'''
 +
<syntaxhighlight lang="XML" line>
 +
<hlayout style="margin-top:20px" width="100%">
 +
<image id="previewImage" width="250px" />
 +
<vlayout hflex="1">
 +
<label id="modelLabel" />
 +
<label id="makeLabel" />
 +
<label id="priceLabel" />
 +
<label id="descriptionLabel" />
 +
</vlayout>
 +
</hlayout>
 +
</syntaxhighlight>
 +
* Line 1: the <code>style</code> attribute allows you to customize component's style with CSS syntax.

Latest revision as of 06:16, 22 December 2023

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.