Difference between revisions of "Template:Tutorial common chapters"

From Documentation
m (Reverted edits by Tmillsclare (talk) to last revision by Arnaud)
m
Line 1: Line 1:
= Objectif du tutoriel =
+
= Tutorial Objective =
Notre application consiste simplement en un catalogue de voitures. Cette application a deux fonctions:
+
Our target application is a simple car catalog application. This application has two functions:
# Chercher des voitures.
+
# Search cars.
#: Entrez un mot-clé dans le champ d'entrée, cliquez <b>Search</b> et les résultats seront affichés dans la liste en dessous.
+
#: Enter a keyword in the input field, click <b>Search</b> and search results will be displayed in the car list below.
# Voir les détails.
+
# View details.
#: Cliquez sur un élément de la liste, la zone sous la liste de voiture affichera alors les détails de la voiture sélectionnée dont le modèle, le prix, une description et un aperçu.
+
#: 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.
  
  
 
[[File:tutorial-searchexample.png| 400px | center]]
 
[[File:tutorial-searchexample.png| 400px | center]]
  
= Échauffement =
 
  
Cette section vous guide pour mettre en place un projet et utiliser ZK dans Eclipse. Si vous voulez d'abord savoir comment construire l'application avec ZK, démarrez d'abord depuis [[#Declaring Domain Class| Declaring Domain Class]]. Pour commencer, nous allons voir comment préparer un environnement pour construire une application web ZK à savoir configurer l'IDE, installer ZK et lancer l'application dans un serveur.
 
  
 +
= Warm Up =
  
==Configurer Eclipse ==
+
This section guides you through how to setup a project and use ZK in Eclipse. If you want to know how to build the application with ZK first, please skip it and start from [[#Declaring Domain Class| Declaring Domain Class]]. 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.
  
Dans ce tutoriel, Eclipse IDE 3.7 (indigo) pour Java EE developer [[File:Eclipse-javaee.png]] est utilisé pour montrer la construction de l'application 'catalogue de voitures'. ([http://www.eclipse.org/downloads/packages/release/indigo/sr2 Télécharger Eclipse] ici, extraire le fichier zip téléchargé dans un dossier et exécuter eclipse.exe pour lancer Eclipse.)
 
  
Pour pouvoir éditer les pages ZK UI dans Eclipse, ajoutez "zul" (nom des extensions des fichiers ZK UI) comme type de contenu de format XML en suivant les étapes suivantes:
+
==Setup Eclipse ==
  
# Sélectionnez '''Window \ Preferences''' pour ouvrir la fenêtre Preferences
+
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.)
# À gauche, sélectionnez '''General --> Content Types'''. À droite, ouvrez le nœud ''Text''' dans la boîte "Content types" et sélectionnez '''XML'''
+
 
# Cliquez sur '''Add''' et ajoutez le type de contenu que vous souhaitez ajouter à savoir '''*.zul''' dans ce cas-ci, ensuite cliquez sur '''OK'''  
+
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]]
 
[[File:Tutorial-add-contenttype.png| 400px | center]]
  
  
Une fois ceci terminé, Eclipse va utiliser l'éditeur XML pour ouvrir votre fichier zul.
+
After this has been done, Eclipse will use XML editor to open your zul file.
  
== Installer ZK dans un Web Project==
+
== Install ZK in a Web Project==
  
'''Télécharger ZK'''
+
'''Download ZK'''
  
[http://www.zkoss.org/download/zk Téléchargez d'abord le ZK CE ] (le nom du fichier sera du genre ''zk-bin-[version].zip'') et extrayez le dans un dossier.
+
[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.
  
  
'''Créer un Project'''
+
'''Create a Project'''
  
Pour construire une application web, il faut d'abord créer un "Dynamic Web Project" dans Eclipse:
+
To build a web application, first, create a "Dynamic Web Project" in Eclipse:
# Sélectionnez '''File \ New \ Dynamic Web Project'''
+
# Select '''File \ New \ Dynamic Web Project'''
# Entrez '''tutorial''' comme nom du Project et laissez le reste par défaut.
+
# Enter '''tutorial''' in Project name and keep everything else default.
  
 
[[File:Tutorial-newproject.png | 400px | center]]
 
[[File:Tutorial-newproject.png | 400px | center]]
  
* Vous pouvez laisser "Target runtime" à "none".
+
* You can leave "Target runtime" as "none".
* Notez que l'on met la valeur de '''Dynamic web module version''' à 3.0 parce-que nous voulons utiliser Servlet 3.0 pour supprimer la configuration de l'application.  
+
* Notice that we set '''Dynamic web module version''' to 3.0 because we want to use Servlet 3.0 to eliminate application configuration.  
  
  
'''Installer ZK JAR'''
+
'''Install ZK JAR'''
  
Pour utiliser ZK dans votre projet, vous devez copier les fichiers ZK JAR dans le dossier des librairies de votre projet.
+
To use ZK in your project, you have to copy ZK JAR files into your project's library folder.
  
Copiez les fichiers JAR depuis le répertoire suivant vers '''WebContent\WEB-INF\lib''':
+
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
 
* {YOUR_ZK_UNZIP_FOLDER}\dist\lib\ext
 
* {YOUR_ZK_UNZIP_FOLDER}\dist\lib\ext
Line 59: Line 61:
 
<div style="-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;color:#c06330;padding:15px 40px;background:#fed no-repeat 13px 13px;margin-bottom:10px
 
<div style="-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;color:#c06330;padding:15px 40px;background:#fed no-repeat 13px 13px;margin-bottom:10px
 
">
 
">
[[File:Icon_info.png ]]    Si vous préférez utiliser un serveur d'applications qui supporte '''des spécifications Servlet (< 3.0)''' plus anciennes ou '''JDK 1.5''', vous devez ajouter des configurations supplémentaires dans web.xml. Merci de vous référer au Guide d'Installation ZK. <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>
+
[[File:Icon_info.png ]]    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>
 
</div>
  
  
'''Créer une page simple'''  
+
'''Create a Simple Page '''  
  
Après l'installation, vous pouvez créer un zul simple pour vérifier que l'installation fonctionne correctement.  
+
After installation, you can create a simple zul to verify if the installation has been successful or not.  
  
Dans Eclipse,  
+
In Eclipse,  
# Sélectionnez '''File \ New \ File''' (or '''File \ New \ Other \ File''' ) pour ajouter un nouveau fichier, '''hello.zul''', dans '''WebContent'''.  
+
# Select '''File \ New \ File''' (or '''File \ New \ Other \ File''' ) to add a new file, '''hello.zul''', under '''WebContent'''.  
# Cliquez sur '''Source''' pour modifier la source.
+
# Click '''Source''' tab to modify source.
 
#: [[File:Tutorial-xmleditor.png| 400px | frame| center|c|creating a zul-file in eclipse's xml editor]]
 
#: [[File:Tutorial-xmleditor.png| 400px | frame| center|c|creating a zul-file in eclipse's xml editor]]
# Copiez et collez l'extrait de code suivant dans hello.zul et enregistrez.  
+
# Copy and paste the following sample code into hello.zul and save.  
  
 
'''hello.zul'''
 
'''hello.zul'''
Line 83: Line 85:
  
  
Maintenant, dans la vue '''Project Explorer''', votre projet devrait ressembler à ceci:
+
Now, in '''Project Explorer''' view your project would look something like:
  
 
[[File:Tutorial-project-structure.png | 200px | center]]
 
[[File:Tutorial-project-structure.png | 200px | center]]
  
Si vous ne trouvez pas la vue '''Project Explorer''', sélectionnez le menu '''Window \ Show View \ Project Explorer''' pour l'ouvrir.
+
If you cannot find '''Project Explorer''' view, select menu '''Window \ Show View \ Project Explorer''' to open it.
  
== Lancer une Application ==
+
== Run an Application ==
 
<!--
 
<!--
 
將 new server 及 run on the server 分成兩個步驟,後面的章節可隨時依照run on the server的步驟執行範例程式
 
將 new server 及 run on the server 分成兩個步驟,後面的章節可隨時依照run on the server的步驟執行範例程式
Line 95: Line 97:
  
  
Avant de lancer une application web, nous devons créer un serveur dans Eclipse. Sélectionnez '''Window \ Preferences''' pour ouvrir la fenêtre Preferences et sélectionnez '''Server \ Runtime Environments''' sur la gauche. Cliquez sur '''Add''' pour ajouter un environnement d'exécution de serveur.
+
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]]
 
[[File:Tutorial-preference-server.png | 400px | center]]
  
  
Sélectionnez '''Apache \ Tomcat v7.0 Server''' vu qu'il supporte Servlet 3.0 et cochez '''Create a new local server''', cliquez ensuite sur '''Next'''.
+
Select '''Apache \ Tomcat v7.0 Server''' as it supports Servlet 3.0 and tick '''Create a new local server''', then click '''Next'''.
  
 
<div style="-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;color:#c06330;padding:15px 40px;background:#fed no-repeat 13px 13px;margin-bottom:10px
 
<div style="-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;color:#c06330;padding:15px 40px;background:#fed no-repeat 13px 13px;margin-bottom:10px
 
">
 
">
[[File:Icon_info.png ]]    Si vous utilisez JDK 1.5, vous pouvez utiliser Tomcat v6.0 mais il faudra faire davantage de configurations dans web.xml. Merci de voir le ZK Installation Guide dans [[#References| References]] .
+
[[File:Icon_info.png ]]    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>
 
</div>
  
Line 111: Line 113:
  
  
Si vous avez précédemment installé Tomcat 7, fournissez simplement le chemin du répertoire. Si vous ne l'avez pas, suivez les étapes suivantes:
+
If you have installed Tomcat 7 previously, simply provide the directory path. If you haven't, proceed with the following steps:
# Cliquez sur '''Download and Install''' et choisissez un répertoire.
+
# Click '''Download and Install''' and choose a folder.
#: '''Notez que le chemin d'installation ne peut contenir aucun caractère non-ASCII.'''
+
#: '''Notice that the installation path must not contain non-ASCII characters.'''
 
#: [[File:Tutorial-downloadinstall.png | 400px | center]]
 
#: [[File:Tutorial-downloadinstall.png | 400px | center]]
# Acceptez la licence et attendez.
+
# Accept the license agreement and wait.
#: '''Eclipse affichera un message d'erreur avant que l'installation ne s'achève, ignorez le.'''
+
#: '''Eclipse will show an error message before installation completes, please ignore this message.'''
 
#: [[File:Tutorial-installing-unknown.png | 400px | center]]
 
#: [[File:Tutorial-installing-unknown.png | 400px | center]]
#: '''Patientez et n'interrompez pas l'installation pour être certain qu'elle s'effectue correctement.'''
+
#: '''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]]
 
#: [[File:Tutorial-installing-progress.png | center]]
#: Eclipse va télécharger et installer Tomcat dans le dossier que vous avez spécifié.   
+
#: Eclipse will download and install Tomcat into the folder you have specified.   
# Lordque l'installation est finie, cliquez sur '''Finish'''
+
# After the installation has been completed, click '''Finish'''
  
  
Vous devriez maintenant voir une nouvelle entrée dans '''Server runtime environments'''.
+
Now you should be able to see a new entry in '''Server runtime environments'''.
  
 
[[File:Tutorial-server-complete.png | 500px | center]]
 
[[File:Tutorial-server-complete.png | 500px | center]]
Line 130: Line 132:
  
  
Faites un clique droit sur hello.zul et sélectionnez '''Run As \ Run on Server''' pour faire tourner ce zul sur un serveur d'applications.
+
Right click on hello.zul and select '''Run As \ Run on Server''' to run this zul on an application server.
  
 
[[File:Tutorial-runonserver.png | 500px | center]]
 
[[File:Tutorial-runonserver.png | 500px | center]]
Line 136: Line 138:
  
  
Choisissez un Tomcat 7. Vous pouvez aussi cocher l'option '''Always use this server when running this project''' pour ne pas devoir choisir un serveur à chaque fois que vous lancerai l'application par la suite. Cliquez sur '''Finish''' et attendez que le serveur démarre.
+
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]]
 
[[File:Tutorial-choose-server.png | 400px | center]]
Line 142: Line 144:
  
  
Une fois le serveur démarré, Eclipse va ouvrir un browser et vous connecter automatiquement à http://localhost:8080/tutorial/hello.zul . Si vous voyez l'image suivante, alors votre projet est prêt pour utiliser ZK.
+
After the server starts running, Eclipse will open a browser and connect to http://localhost:8080/tutorial/hello.zul automatically . If you can see the following image, then your project is ready to use ZK.
  
 
[[File:Tutorial-hello.png | 400px | center]]
 
[[File:Tutorial-hello.png | 400px | center]]
  
Vous pouvez revenir ici et suivre à nouveau ces étapes pour lancer votre application au cours de ce tutoriel
+
You can come back and follow these steps to run your application during this tutorial
  
== Importer et lancer l'Application exemple ==
+
== Import and Run Example Application ==
  
Nous avons préparé un ficher zip projet Eclipse qui contient le code source complet, vous pouvez le télécharger et l'importer dans votre Eclipse sans avoir à démarrer tout de 0.  
+
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.  
  
Pour utiliser l'application exemple, suivez les étapes suivantes:
+
To use example application, follow the steps below:
# [http://sourceforge.net/projects/zkbook/files/GettingStarted/getzkup-20131127.zip/download Téléchargez le fichier zip du projet].  
+
# [http://sourceforge.net/projects/zkbook/files/GettingStarted/getzkup-20131127.zip/download Download example application project zip file].  
# Dans Eclipse, sélectionnez '''File \ Import \ General \ Existing Projects into Workspace''', choisissez '''Select archive file''' pour importer le zip de l'application comme  projet dans Eclipse.  
+
# 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.  
# Suivez ensuite les instructions de [[#Run an Application |Run an Application]] pour lancer l'application.
+
# Then follow the instructions from [[#Run an Application |Run an Application]] to run it.
  
 
<!--
 
<!--
Nous décrivons les objets domaine ici pcq cette section est indépendante des sections MVC et MVVM et la partie domaine est identique pour ces 2 design patterns.
+
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.
 
-->
 
-->
  
= Déclaration des classes du domaine =
+
= Declaring Domain Class =
  
Ce qui suit est l'objet du domaine qui représente une voiture.  
+
The following is the domain object that represents a car.  
  
 
<source lang="java">
 
<source lang="java">
Line 177: Line 179:
 
}
 
}
 
</source>
 
</source>
* Merci de vous référer à la section References pour voir le code complet. <ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/Car.java Car.java] </ref>
+
* Please refer to References section to see the complete code. <ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/Car.java Car.java] </ref>
  
On définit ensuite une classe de service pour effectuer la logique business (chercher des voitures) tel que montré ci-dessous:
+
We then define a service class to perform the business logic (search cars) shown below:
  
 
<source lang="java">
 
<source lang="java">
Line 199: Line 201:
 
</source>
 
</source>
  
Dans cet exemple, nous avons défini une classe - <tt>CarServeImpl</tt> qui implémente l'interface ci-dessus. Par soucis de simplicité, elle utilise une liste objet statique comme modèle de données. Vous pouvez la réécrire de sorte qu'elle se connecte à une base de données dans une application réelle. Les détails de l'implémentation ne sont pas l'objet de cet article, merci de vous référer à la section References.<ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/CarService.java CarService.java] [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/CarServiceImpl.java CarServiceImpl.java] </ref>
+
In this example, we have defined a class - <tt>CarServeImpl</tt> 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. Implementation details are not in the scope of this article, please refer to References section.<ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/CarService.java CarService.java] [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/src/tutorial/CarServiceImpl.java CarServiceImpl.java] </ref>
  
=Construire l'interface utilisateur =
+
=Building the User Interface =
  
Le design de l'UI est un bon début pour construire une application vu qu'il vous aide à définir l'étendue de votre application. ZK fournit des centaines de composants UI prêts à l'emploi de sorte que les développeurs peuvent rapidement construire l'interface utilisateur de leur choix en combinant et en mélangeant ces composants sans avoir à les créer.  
+
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.  
  
Dans ZK, vous pouvez utiliser ZK User Interface Markup Language (ZUML) <ref> [[ZUML Reference|ZUML Reference]] </ref>, un langage formaté XML, pour décrire les UI. Suivant la convention ZK, les fichiers décrivant les UI avec ZUML utilisent comme suffixe '''.zul'''. Dans les fichiers zul, un composant peut être représenté comme un élément XML (tag) et vous pouvez configurer pour chaque composant son style, son comportement et sa fonction via les attributs XML de cet élément.<ref> [[ZK Component Reference|ZK Component Reference]] </ref>  
+
In ZK, you can use ZK User Interface Markup Language (ZUML) <ref> [[ZUML Reference|ZUML Reference]] </ref>, 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.<ref> [[ZK Component Reference|ZK Component Reference]] </ref>  
  
Dans cet exemple, nous voulons d'abord concevoir une fenêtre avec un titre spécifique et un bord normal qui sera la fenêtre de notre application.
+
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.
  
  
'''Extrait de search.zul'''
+
'''Extracted from search.zul'''
 
<source lang="xml">
 
<source lang="xml">
  
Line 218: Line 220:
 
</source>
 
</source>
  
Vu que ''window'' et le composant 'englobant' principal, il est appelé ''root component''. ''Window'' est un container souvent utilisé parce-que c'est un élément d'affichage de base d'une application de type bureau et qui peut en même temps contenir d'autres composants. Tous les autres composants inclus dans ''window'' sont appelés ''child components'' et doivent être placés dans le body de la fenêtre. Nous mettons un texte dans la barre de titre de ''window''' grâce à l'attribut "title" et nous faisons en sorte que ''window'' s'affiche avec un bord normal grâce à l'attribut "border". Pour l'attribut "width", utilisez une syntaxe de type CSS comme "800px" ou "60%".
+
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%".
  
  
De base, l'UI de notre application est divisée en 3 zones à l'intérieur de ''window'' qui sont, de haut en bas, la fonction de recherche, la liste des voitures et les détails de la voiture.
+
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.
  
 
[[File:Tutorial-ui-3areas.png | 400px |center]]
 
[[File:Tutorial-ui-3areas.png | 400px |center]]
  
  
'''Zone de recherche:'''
+
'''Search Area:'''
Les composants ZK sont comme des blocs à construire, vous pouvez combiner et mélanger les composants existants pour construire l'UI de votre choix. Pour permettre aux utilisateurs d'effectuer des recherches, il faut un texte incitant les utilisateurs à entrer une valeur, un endroit pour qu'ils tapent effectivement cette valeur-clé et un bouton qui va déclencher la recherche. Nus pouvons utiliser dans ce but les composants ZK suivants:
+
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:
  
'''Extrait de search.zul'''
+
'''Extracted from search.zul'''
 
<source lang="xml">
 
<source lang="xml">
  
Line 240: Line 242:
 
</source>
 
</source>
  
<tt>hbox</tt> est un composant de layout qui organise ses enfants de manière horizontale et vous avez donc deviné que le '''h''' signifie ''horizontal''. Vu que ces composants enfants ont des hauteurs différentes, nous mettons la valeur "center" à l'attribut "align" pour les aligner sur une ligne centrale. On spécifie aussi ici un attribut "id" pour certains composants de manière à pouvoir ensuite les contrôler grâce à cet ''id''. Vous pouvez aussi facilement afficher une image sur le bouton en spécifiant le chemin de celle-ci dans l'attribut "image".  
+
<tt>hbox</tt> 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 for the "image" attribute.  
  
  
'''Zone de liste des voitures.'''
+
'''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: Model, Make 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 label to demonstrate structure of a ''listitem'', and we'll talk about how to create ''listitem'' dynamically with respect to each data object in the next chapter.
ZK fournit quelques composants qui permettent d'afficher des collections de données comme ''listbox'', ''grid'', et ''tree''. Dans cet exemple, nous allons utiliser une ''listbox'' pour afficher une liste de voitures sur 3 colonnes: Model, Make et Price. Nous mettons l'attribut "height" à une valeur qui limite le nombre de lignes à une hauteur spécifiée; vous pouvez bouger la scroll-bar pour visualiser les autre lignes. L'attribut "emptyMessage" est utilisé pour afficher un message lorsque la ''listbox'' ne contient aucun élément. La ''listbox'' est un composant container et vous pouver ajouter ''listhead'' pour définir une colonne. Le ''listitem'' est utilisé pour afficher les données et le nombre de ''listcell'' dans un ''listitem'' doit être égal au nombre de ''listheader''. On utilise ici ''listcell'' avec un label statique pour montrer la structure d'un ''listitem'' et nous verrons comment créer dynamiquement un ''listitem'' qui respecte chaque objet de données dans le chapitre suivant.
 
  
'''Extrait de search.zul'''
+
'''Extracted from search.zul'''
 
<source lang="xml">
 
<source lang="xml">
 
<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
 
<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
Line 263: Line 264:
  
  
'''Zone de détail des voiture.'''
+
'''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.
Comme ''hbox'', ''vbox'' est aussi un composant de layout qui arrange ses composants enfants en ordre vertical. En combinant ces 2 composants de layout, nous pouvons présenter davantage d'informations sur un écran. L'attribut "style" vous permet de customiser le style du composant avec une syntaxe CSS.
 
  
'''Extrait de search.zul'''
+
'''Extracted from search.zul'''
 
<source lang="xml">
 
<source lang="xml">
 
<hbox style="margin-top:20px">
 
<hbox style="margin-top:20px">
Line 280: Line 280:
  
  
Vous pouvez visualiser le fichier zul complet grâce au lien dans la section References. <ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/WebContent/search.zul search.zul] </ref>
+
You can see the complete zul file through the link in the References section. <ref> [https://code.google.com/p/zkbooks/source/browse/trunk/gettingStarted/getZkUp/WebContent/search.zul search.zul] </ref>

Revision as of 09:20, 10 April 2014

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


Warm Up

This section guides you through how to setup a project and use ZK in Eclipse. If you want to know how to build the application with ZK first, please skip it and start from Declaring Domain Class. 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 Eclipse-javaee.png 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:

  1. Select Window \ Preferences to open Preferences window
  2. On the left, select General --> Content Types. On right, expand Text node in "Content types" box and select XML
  3. Click Add and type in the content type you wish to add which is *.zul in this case, then click OK
Tutorial-add-contenttype.png


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:

  1. Select File \ New \ Dynamic Web Project
  2. Enter tutorial in Project name and keep everything else default.
Tutorial-newproject.png
  • 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


Icon info.png 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,

  1. Select File \ New \ File (or File \ New \ Other \ File ) to add a new file, hello.zul, under WebContent.
  2. Click Source tab to modify source.
    creating a zul-file in eclipse's xml editor
  3. 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:

Tutorial-project-structure.png

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.

Tutorial-preference-server.png


Select Apache \ Tomcat v7.0 Server as it supports Servlet 3.0 and tick Create a new local server, then click Next.

Icon info.png 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 .

Tutorial-newserver.png


If you have installed Tomcat 7 previously, simply provide the directory path. If you haven't, proceed with the following steps:

  1. Click Download and Install and choose a folder.
    Notice that the installation path must not contain non-ASCII characters.
    Tutorial-downloadinstall.png
  2. Accept the license agreement and wait.
    Eclipse will show an error message before installation completes, please ignore this message.
    Tutorial-installing-unknown.png
    Please wait and do not interrupt the installation before it completes to ensure that the installation has been done properly.
    Tutorial-installing-progress.png
    Eclipse will download and install Tomcat into the folder you have specified.
  3. After the installation has been completed, click Finish


Now you should be able to see a new entry in Server runtime environments.

Tutorial-server-complete.png


Right click on hello.zul and 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 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.

Tutorial-choose-server.png


After the server starts running, Eclipse will open a browser and connect to http://localhost:8080/tutorial/hello.zul automatically . If you can see the following image, then your project is ready to use ZK.

Tutorial-hello.png

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:

  1. Download example application project zip file.
  2. In Eclipse, select File \ Import \ General \ Existing Projects into Workspace, choose Select archive file to import example application zip file as a project into your Eclipse.
  3. Then follow the instructions from Run an Application to run it.


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
}
  • 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  model and make.
	 * @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 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.

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

	 	<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 for the "image" attribute.


Car List Area. ZK provides several components to display a collection of data such as listbox, grid, and tree. In this example, we have chosen to use a listbox to display a list of cars with 3 columns: Model, Make 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 label to demonstrate structure of a listitem, and we'll talk about how to create listitem dynamically with respect to each data object in the next chapter.

Extracted from search.zul

	 	<listbox id="carListbox" height="160px" emptyMessage="No car found in the result">
			<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>


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="modelLabel" />
				<label id="makeLabel" />
				<label id="priceLabel" />
				<label id="descriptionLabel"/>
			</vbox>
		</hbox>


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