0% found this document useful (0 votes)
6 views

ZK - ZK Getting Started-Tutorial - Documentation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

ZK - ZK Getting Started-Tutorial - Documentation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.

org/wiki/ZK_Getting_Started/Tutorial

Products

ZK Framework
ZK Spreadsheet
ZK Charts
ZK Pivottable
ZK Studio
ZK Calendar
ZK Spring
ZK JSP
ZATS Test

Demos

ZK Framework
ZK SpreadSheet
ZK Pivottable
ZK Charts
ZK Calendar
ZK Web Mail
ZK Sandbox
Real World Apps

Downloads

ZK Framework
ZK Spreadsheet
ZK Charts
ZK Pivottable
ZK Studio
ZK Calendar
ZK Spring
ZK JSP
ZATS Test

Why ZK

Top Reasons
Features
Why ZK EE
Who's Using
Case Studies
Testimonials

1 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

Community

Forum
Blog
Board
Request Features
Report Bugs

Documentation

ZK Framework
ZK Spreadsheet
ZK Charts
ZK Pivottable
ZK Studio
ZK Calendar
ZK Spring
ZK JSP
ZATS Test

Support

Support Options
Partners
About Us
Contact Us

Search..

Custom Search Wiki Search

From Documentation

This tutorial guides you through the most fundamental features and concepts of ZK.

To create web application, please refer to Create and Run Your First ZK Application with Eclipse and ZK
Studio (http://books.zkoss.org/wiki/ZK_Installation_Guide/Quick_Start
/Create_and_Run_Your_First_ZK_Application_with_Eclipse_and_ZK_Studio)
For product description, please refer to the ZK product page (http://www.zkoss.org/product/zk) and the
feature list (http://www.zkoss.org/whyzk/features) .
For a real world example, please refer to Creating a database-driven application.
For learning step-by-step, please refer to ZK Essentials.

2 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

Contents
1 Hello World!
2 Say Hello in Ajax way
3 It is Java that runs on the server
4 A component is a POJO
5 A component is a LEGO brick
6 Express data with variable resolver and EL expressions
7 MVC: Separate code from user interface
8 MVC: Autowire UI objects to data members
9 MVVM: Automate the access with data binding
10 Define UI in pure Java
11 Adding client-side functionality
12 Architecture overview

Hello World!
After ZK is installed on your favorite Web server[1], writing applications is straightforward. Just create a ZUML
file[2], and name it as hello.zul[3], under one of the Web application's directories just as you would do for an
HTML file.

1 <window title="My First ZK Application" border="normal">


2 Hello World!
3 </window>

Assuming the name of the Web project is myapp, then go to the corresponding URL, which is http://localhost
/myapp/hello.zul, and you'll see your first ZK application running.

On a ZUML page, an XML element describes what a component[4] can create while the XML attributes are used
to assign values to a component's properties. In this example, a window component is created and its title is set
to "My First ZK Application" and its border is set to normal.

The text enclosed in the XML elements can also be interpreted as a special component called label. Thus, the
above example is equivalent to the following code:

1 <window title="My First ZK Application" border="normal">


2 <label value="Hello World!"/>
3 </window>

1. ↑ Please refer to ZK Installation Guide.


2. ↑ ZUML [1] (http://books.zkoss.org/wiki/ZUML%20Reference/ZUML)

3 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

3. ↑ The other way to try examples is to use ZK Sandbox (http://www.zkoss.org/zksandbox/) to


run them.
4. ↑ Interface : Component

Say Hello in Ajax way


Let us put some interactivity into it.

1 <button label="Say Hello" onClick='Messagebox.show("Hello World!")'/>

Then, when you click the button, you'll see the following:

The onClick attribute is a special attribute used to add an event listener(EventListener) to the component such
as that it is invoked when an end user clicks the component. The attribute value could be any legal Java code.
Notice that it is NOT JavaScript, and you have to use double quotes (") in a string. To escape a double quote in
an XML string, you could use single quotes (') to enclose it[1].

Here we invoke Messagebox.show(String) to display a message box shown above.

The Java code is interpreted by BeanShell (http://www.beanshell.org/) at runtime. In addition to event handling,
you could embed the code in a ZUML page by specifying it in a special element called zscript. For example,
you could simply define a function in the code as the following:

1 <window title="My First ZK Application" border="normal">


2 <button label="Say Hello" onClick='alert("Hello World!")'/>
3 <zscript>
4 void alert(String message){ //declare a function
5 Messagebox.show(message);
6 }
7 </zscript>
8 </window>

In fact, alert is a built-in function that you can use directly from the embedded Java code.

1. ↑ If you are not familiar with XML, you might take a look at the XML background section.

It is Java that runs on the server


The embedded Java code runs on the server so as to gain easy access to any resources available on the server.

4 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

For example,

1 <window title="Property Retrieval" border="normal">


2 Enter a property name: <textbox/>
3 <button label="Retrieve" onClick="alert(System.getProperty(self.getPreviou
4 </window>

where self is a built-in variable which refers a component receiving the event.

If you enter java.version and then click the button, the result will be shown as the following:

A component is a POJO
A component is a POJO. You could instantiate and manipulate them directly. For example, you could generate
the result by instantiating component(s) to represent it, and then append them to another component as shown
below.

1 <window title="Property Retrieval" border="normal">


2 Enter a property name: <textbox id="input"/>
3 <button label="Retrieve"
4 onClick="result.appendChild(new Label(System.getProperty(input.getValue()
5 <vlayout id="result"/>
6 </window>

Once appended, the components can be displayed in the browser automatically. Similarly, if components are
detached, they are removed from the browser automatically.

In addition, you could change the state of a component directly. All modifications will be synchronized back to
the browser automatically.

1 <window title="Property Retrieval" border="normal">


2 Enter a property name: <textbox id="input"/>
3 <button label="Retrieve"
4 onClick="result.setValue(System.getProperty(input.getValue()))"/>
5 <separator/>
6 <label id="result"/>
7 </window>

A component is a LEGO brick

5 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

Instead of introducing different components for different purposes, our components are designed to build blocks.
You are free to compose blocks together to realize sophisticated UI without customizing any components. For
example, you could put anything in a grid, including grid itself; anything in any layout, including the layout
itself. Please see our demo (http://www.zkoss.org/zkdemo) for more examples.

Express data with variable resolver and EL expressions


On a ZUML page, you could locate data with a variable resolver (VariableResolver), and then express it with EL
expressions.

For example, assumes that we have a class called foo.Users, and we can retrieve a list of users by employing
its static method called getAll(). Then, we can implement a variable resolver as follows.

1 package foo;
2 public class UserResolver implements org.zkoss.xel.VariableResolver {
3 public Object resolveVariable(String name) {
4 return "users".equals(name) ? Users.getAll(): null;
5 }
6 }

And, we can list all users as follows.

1 <?variable-resolver class="foo.UserResolver"?>
2 <grid>
3 <columns>
4 <column label="Name" sort="auto"/>
5 <column label="Title" sort="auto"/>
6 <column label="Age" sort="auto"/>
7 </columns>
8 <rows>
9 <row forEach="${users}">
10 <label value="${each.name}"/>
11 <label value="${each.title}"/>
12 <label value="${each.age}"/>
13 </row>
14 </rows>
15 </grid>

There are three methods that we can assume foo.User: getName(), getTitle() and getAge(). forEach is
used to instantiate components by iterating through a collection of objects.

6 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

MVC: Separate code from user interface


Embedding Java code in a ZUML page is straightforward and easy for prototyping. However, in a production
environment, it is better to separate the code from user interfaces. The code can be compiled at the development
time. It is easier to develop and test, and runs much faster than the embedded code which is interpreted at
runtime.

To separate codes from UI, you can implement a Java class (aka., the controller) that implements Composer, and
then handle UI in Composer.doAfterCompose(Component). For example, you can redo the previous example by
registering an event listener in Composer.doAfterCompose(Component), and then retrieve the result by
instantiating a label to represent it in the event listener as follows.

1 package foo;
2 import org.zkoss.zk.ui.Component;
3 import org.zkoss.zk.ui.util.Composer;
4 import org.zkoss.zk.ui.event.EventListener;
5 import org.zkoss.zul.Label;
6
7 public class PropertyRetriever implements Composer {
8 public void doAfterCompose(final Component target) { //handle UI here
9 target.addEventListener("onClick", new EventListener() { //add a even
10 public void onEvent(Event event) {
11 String prop = System.getProperty(((Textbox)target.query(
12 target.query("#result").appendChild(new Label(prop));
13 }
14 });
15 }
16 }

As shown, an event listener could be registered with the use of Component.addEventListener(String,


EventListener). An event listener must implement EventListener, and then handle the event in
EventListener.onEvent(org.zkoss.zk.ui.event.Event.

Also notice that a component could be retrieved with the use of Component.query(String), which allows the
developer to use a CSS 3 selector to select a component, such as query("#id1 grid textbox").

Then, you could associate the controller (foo.PropertyRetriever) with a component using the apply attribute
as shown below.

1 <window title="Property Retrieval" border="normal">


2 Enter a property name: <textbox id="input"/>
3 <button label="Retrieve" apply="foo.PropertyRetriever"/>
4 <vlayout id="result"/>
5 </window>

For more information, please refer to Get ZK Up and Running with MVC (http://books.zkoss.org
/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVC)

MVC: Autowire UI objects to data members


Implementing and registering event listeners is a bit tedious. Thus, ZK provides a feature called autowiring. By

7 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

extending from SelectorComposer, ZK looks for the members annotated with @Wire or @Listen to match the
components. For example, you could rewrite foo.PropertyRetriever by utilizing the autowriing as follows.

PropertyRetriever.java
1 package foo;
2 import org.zkoss.zk.ui.Component;
3 import org.zkoss.zk.ui.event.Event;
4 import org.zkoss.zk.ui.select.SelectorComposer;
5 import org.zkoss.zk.ui.select.annotation.*;
6 import org.zkoss.zul.*;
7
8 public class PropertyRetriever extends SelectorComposer<Window> {
9 @Wire
10 Textbox input; //wired to a component called input
11 @Wire
12 Vlayout result; //wired to a component called result
13
14 @Listen("onClick=#retrieve")
15 public void submit(Event event) { //register a listener to a component ca
16 String prop = System.getProperty(input.getValue());
17 result.appendChild(new Label(prop));
18 }
19 }

and the ZUL page is as follows.

1 <window title="Property Retrieval" border="normal" apply="foo.PropertyRetrieve


2 Enter a property name: <textbox id="input"/>
3 <button label="Retrieve" id="retrieve"/>
4 <vlayout id="result"/>
5 </window>

As shown above, @Wire will cause input and result to be wired automatically, such that you could access the
components directly. Also @Listen("onClick=#retrieve") indicates that the annotated method will be
registered as an event listener to the component called retrieve to handle the onClick event.

If the component's ID is different from the member's name or the pattern is complicated, you could specify a
CSS 3 selector such as @Wire("#id"), <code>@Wire("window > div > button") and @Listen("onClick
= button[label='Clear']").

You can use with Spring or CDI managed bean in the composer too. For example,

1 @VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver)
2 public class PasswordSetter extends SelectorComposer<Window> {
3 @WireVariable //wire Spring managed bean
4 private User user;
5 @Wire
6 private Textbox password; //wired automatically if there is a textbox nam
7
8 @Listen("onClick=#submit")
9 public void submit() {
10 user.setPassword(password.getValue());
11 }

8 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

12 }

Notice : MVC pattern is recommended for a production application. On the other hand, to
maintain readability, many examples in our documents embed code directly into ZUML pages.

MVVM: Automate the access with data binding


EL expressions are convenient but they are limited to display read-only data. If you allow end users to modify
data (such as CRUD), or change how the data can be displayed based on users' selection, you could use ZK data
binding to handle the display and modification automatically for you. All you need to do is to implement a
so-called ViewModel (a POJO) that provides the data beans and/or describes relationship between UI and data
beans[1]. For example,[2].

1 package foo;
2 public class UserViewModel {
3 List<User> users = Users.getAll();
4
5 public List<User> getUsers() {
6 return users;
7 }
8 }

Then, you could put them together by applying a built-in composer called BindComposer in a ZUML document
as follows.

1 <grid apply="org.zkoss.bind.BindComposer"
2 viewModel="@id('vm') @init('foo.UserViewModel')" model="@bind(vm.users)"
3 <columns>
4 <column label="Name" sort="auto" />
5 <column label="Title" sort="auto" />
6 <column label="Age" sort="auto" />
7 </columns>
8 <template name="model" var="user">
9 <row>
10 <textbox value="@bind(user.name)" />
11 <textbox value="@bind(user.title)" />
12 <intbox value="@bind(user.age)" />
13 </row>
14 </template>
15 </grid>

9 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

Please notice that you do not need to write any code to handle the display or modification. Rather, you declare
the relation of the UI and data beans in annotations, such as @bind(user.name). Any modification made to each
input (by the end user) is stored back to the object (foo.User) automatically and vice versa, assuming that the
POJO has the required setter methods, such as setName(String).

For more information, please refer to Get ZK Up and Running with MVVM (http://books.zkoss.org
/wiki/ZK_Getting_Started/Get_ZK_Up_and_Running_with_MVC)

1. ↑ ZK data binding is based on the MVVM design pattern, which is identical to the
Presentation Model (http://martinfowler.com/eaaDev/PresentationModel.html) introduced by
Martin Fowler. For more information, please refer to ZK Developer's Reference: MVVM.
2. ↑ Here we load the users by assuming there is a utility called Users. However, it is
straightforward if you'd like to wire Spring-managed or CDI-managed beans. For more
information, please refer to ZK Developer's Reference: MVC

Notice : MVVM pattern applies to ZK 6 and later

Define UI in pure Java


In additions to XML, developers could also define UI in pure Java. For example, you could implement the
property-retrieval example as follows.

1 public class PropertyRetrieval extends GenericRichlet {


2 public void service(Page page) throws Exception {
3 final Window main = new Window("Property Retrieval", "normal", false
4 main.appendChild(new Label("Enter a property name: "));
5
6 final Textbox input = new Textbox();
7 input.setId("input");
8 main.appendChild(input);
9
10 final Button button = new Button("Retrieve");
11 button.addEventListener("onClick",
12 new EventListener() {
13 public void onEvent(Event event) throws Exception {
14 Messagebox.show(System.getProperty(input.getValue()));

10 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

15 }
16 });
17 main.appendChild(button);
18
19 main.setPage(page); //attach so it and all descendants will be genera
20 }
21 }

A richlet (Richlet) is a small Java program that creates all necessary user interfaces for a given page in response
to users' request. Here we extend java.lang.Object from a skeleton called GenericRichlet. Then, we create all the
required components in Richlet.service(Page).

Adding client-side functionality


In addition to handling events and components on the server, ZK also provides an option allowing developers to
control UI from the client side. We have dubbed this blending of technology, Server+client Fusion.

For example, we could re-implement the Hello World example with the code from the client side as follows.

1 <button label="Say Hello" w:onClick='jq.alert("Hello World!")' xmlns:w="client

where we declare a XML namespace (http://www.w3schools.com/xml/xml_namespaces.asp) named client to


indicate the event handler which will be evaluated at the client side. In addition, jq.alert(String, Map) is a
client-side method equivalent to Messagebox.show(String).

All components are available and accessible to the client. For example, here is a number guessing game that
manipulates UI from the client side.

1 <window title="Guess a number" border="normal">


2 <vlayout>
3 Type number between 0 and 99 and then press Enter to guess:
4 <intbox w:onOK="guess(this)" xmlns:w="client"/>
5 </vlayout>
6 <script><![CDATA[
7 var num = Math.floor(Math.random() * 100);
8 function guess(wgt) {
9 var val = wgt.getValue(),
10 mesg = val > num ? "smaller than " + val:
11 val < num ? "larger than "+val: val + " is correct!";
12 wgt.parent.appendChild(new zul.wgt.Label({value: mesg}));
13 wgt.setValue("");
14 }
15 ]]></script>
16 </window>

where onOK is an event fired when the user presses Enter, and script is used to embed the client-side code (in
contrast to zscript for embedding the server-side code).

11 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

Architecture overview

When a ZK application runs on the server, it gives access to backend resources, assemble UI with components,
listen to users' activity, and then manipulate components to update UI. All are done on the server. The
synchronization of the states of the components between the browser and the server is done automatically by ZK
and transparently to the application.

When running on the server, the application can access full Java technology stack. Users' activities, including
Ajax and Server Push, are abstracted to event objects. UI are composed of POJO-like components. It is the most
productive approach to develop a modern Web application.

With ZK's Server+client Fusion architecture, your application will never stop running on the server. You can
enhance your application's interactivity by adding optional client-side functionality, such as client-side event
handling, visual effect customizing and even UI composing without server-side coding. ZK is the only
framework to enable seamless fusion from pure server-centric to pure client-centric. You can have the best of
two worlds: productivity and flexibility.

Last Update : 2014/9/26

12 of 13 20/01/2017 17:27
ZK - ZK Getting Started/Tutorial - Documentation https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial

Retrieved from "https://www.zkoss.org/wiki/ZK_Getting_Started/Tutorial"

Page |
Discussion |
View source |
History

Like Share 116 people like this. Be the first of your friends.
Tweet

Follow us via :
ZK RSS
StumbleUpon
ZK LinkedIn Group
twitter @zkoss
facebook fan page

Log in

What links here |


Related changes |
Special pages
| Recent changes
| Help

This page was last modified on 26 September 2014, at 04:33.


This page has been accessed 240,521 times.
Disclaimers | Modified by ZK
Partners :
Partners

13 of 13 20/01/2017 17:27

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy