java.net member

Rechercher dans ce site

Templates in JSF2

>> 02 December 2010

Le même article en français

Templates let you have a common layout or look used by multiple views.

Say you have a killer layout for your site, you want to use it with all your views. Without any change, or with customization.

Using a common stylesheet is good, but not a whole solution. What if you need to use exactly the same structure. Here is an example

jsf_style.css
<!--
/* Masthead */
#masthead {
position:relative;
padding:10px;
background-color:#FFF;
height: 50px;
border: 1px #000 solid;
margin-right:18%;
}

/********************************************************************************
Sidebar
*******************************************************************************/
/* Sidebar */
#sidebar {
float:left;
padding:12px;
width:14%;
background-color:#fcb968;
border: 1px #c0c0c0 solid;
}

/********************************************************************************
Content
*******************************************************************************/
/* Content */
#content {
position:relative;
margin-left:16%;
margin-right:18%;
padding:12px;
border: 2px #fcb968 solid;
}
-->

layout.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK REL="StyleSheet" HREF="stylesheets/jsf_style.css" TYPE="text/css" />

<title>Using templates in JSF 2</title>
</head>
<body>
<!-- +++++++++++++++++++++++++++++++++MASTHEAD+++++++++++++++++++++++++++-->
<div id="masthead">
<h1 align="center">Using templates in JSF 2</h1>
</div>

<!-- +++++++++++++++++++++++++++ SIDEBAR AND LINKS +++++++++++++++++++++++++ -->
<div id="sidebar">
<p><a href="#">Formations</a></p>

<p><a href="#">Testing</a></p>

<p><a href="#">JSF 2</a></p>

</div>

<!-- +++++++++++++++++++++++++CONTENT++++++++++++++++++++++++++++++++++++++++ -->

<div id="content">
<p>Line1</p>
<p>Line2</p>
<p>Line3</p>
</div>
</body>
</html>

Display

To create a template
  • Insert a namespace instruction
        xmlns:ui="http://java.sun.com/jsf/facelets"

  • For every place you want to customize put a "ui:insert" instruction with an attribute "name". The body of <u:insert can be overridden from a composition using <ui:define

  • <ui:insert without a body has simply no default value
Example :
To use the previous example "layout.xhtml" as a template and customize the header of every composition (file that uses the template) :

  • Add <ui:insert with a body. The same name attribute, will be used in the composition to override the body (with the instruction <ui:define). Note that the styling instruction (h1) is now outside <ui:insert>. If you do not provide a <ui:define name="header" the template will use the default <ui:insert> body. The same thing is done for <title>

<h1 align="center">
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</h1>

  • Create a composition, call it formation.xhtml (see create composition later) and define a content for the <ui:insert name="header"
layout.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"

xmlns:f="http://java.sun.com/jsf/core"

xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"

>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK REL="StyleSheet" HREF="stylesheets/jsf_style.css" TYPE="text/css" />

<title>
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</title>
</head>
<body>
<!-- +++++++++++++++++++MASTHEAD++++++++++++++++++++++++++++++++++++++++++++ -->
<div id="masthead">

<h1 align="center">
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</h1>

</div>

<!-- +++++++++++++++++++SIDEBAR AND LINKS ++++++++++++++++++++++++++++++++++ -->
<div id="sidebar">
<p><a href="formation.jsf">Formations</a></p>

<p><a href="#">Testing</a></p>

<p><a href="#">JSF 2</a></p>

</div>

<!-- ++++++++++++++++++++++CONTENT++++++++++++++++++++++++++++++++++++++++++ -->

<div id="content">
<p>Line1</p>
<p>Line2</p>
<p>Line3</p>
</div>
</body>
</html>
formation.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Formation in JSF 2 (Learning)
</ui:define>
</ui:composition>

Note:
All parties of "layout.xhtml" that are not customized by <ui:isert> stay as is.
The header has now changed.

Display

Note:
In the same way, we can create another composition that uses the template with another custom header. Another composition for instance index.xhtml that does not provide a <ui:define name="header" will still use the default header value defined in the template.

testing.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Testing
</ui:define>
</ui:composition>


Display

index.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">

</ui:composition>
Display

I don't want a default in template
If you want to customize a section in the template without using a default text or style, you can use <ui:insert without a body. <ui:composition stays the same.

Example

The party content has no default now. Text is different in compositions, and formation.xhtml uses <ol>

layout.xhtml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"

xmlns:f="http://java.sun.com/jsf/core"

xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"

>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK REL="StyleSheet" HREF="stylesheets/jsf_style.css" TYPE="text/css" />

<title>
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</title>
</head>
<body>
<!-- +++++++++++++++++++++MASTHEAD++++++++++++++++++++++++++++++++++++++ -->
<div id="masthead">

<h1 align="center">
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</h1>

</div>

<!-- ++++++++++++++SIDEBAR AND LINKS +++++++++++++++++++++++++++++++++++++++ -->
<div id="sidebar">
<p><a href="formation.jsf">Formations</a></p>

<p><a href="#">Testing</a></p>

<p><a href="#">JSF 2</a></p>

</div>

<!-- +++++++++++++++++++++++CONTENT++++++++++++++++++++++++++++++++++++++++ -->

<div id="content">
<ui:insert name="content" />
</div>
</body>
</html>

testing.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Testing
</ui:define>
<ui:define name="content">
<p>Line1 in Testing</p>
<p>Line2 in Testing</p>
<p>Line3 in Testing</p>
</ui:define>
</ui:composition>

Display

formation.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Formation in JSF 2 (Learning)
</ui:define>
<ui:define name="content">
<ol>
<li>Line1 in Testing</li>
<li>Line2 in Testing</li>
<li>Line3 in Testing</li>
</ol>
</ui:define>
</ui:composition>

Display

How to create a composition
  • Use <ui:composition. "template" attribute's value is the full path to the template created previously.

       <ui:composition xmlns="http://www.w3.org/1999/xhtml"
       xmlns:ui="http://java.sun.com/jsf/facelets"
       template="layout.xhtml">
       ...
       ...
       </ui:composition>

  • Inside the composition use <ui:define to override, or replace every <ui:insert you want to customize in the template.

         <ui:composition>
         ...
        <ui:define name="header">
        Testing
        </ui:define>
        ...
        </ui:composition>

Going further using <ui:include
If the text in <ui:define> is composed of more that one or two sentences, or even if it's only a sentence that you want to define it once to keep maintenance easy, you can use <ui:include>.

Using <ui:include is straightforward. You give it as a "src" the path to the file to be included

Example :
formation.xhtml and testing.xhtml will use <ui:include to include another composition file "header.xhtml".

Note:
The file extension is .xhtml in <ui:include
<title> in template.xhtml does not use <ui:insert anymore

header.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">

<h:graphicImage url="images/logo.gif" width="100px" />
<br/>
<h:outputText value="http://www.java-javafx.com"/>

</ui:composition>

formation.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
<ui:include src="header.xhtml">
</ui:include>
<br/>
Formation in JSF 2 (Learning)
</ui:define>
<ui:define name="content">
<ol>
<li>Line1 in Testing</li>
<li>Line2 in Testing</li>
<li>Line3 in Testing</li>
</ol>
</ui:define>
</ui:composition>

testing.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
<ui:include src="header.xhtml">
</ui:include>
<br/>
Testing
</ui:define>
<ui:define name="content">
<p>Line1 in Testing</p>
<p>Line2 in Testing</p>
<p>Line3 in Testing</p>
</ui:define>
</ui:composition>


Display

Summary :

To create a template
=====================
-Insert a namespace instruction
xmlns:ui="http://java.sun.com/jsf/facelets"

-For every place you want to customize put a "ui:insert" instruction with an attribute "name".
This <ui:insert is replaced with the value of a <ui:define in a composition
The body of <u:insert can be used as a default text, if the <ui:define for the same name attribute is absent

<ui:insert name="attribute_name1" /> no default
or
<ui:insert name="attribute_name2">
Default text
</ui:insert>

How to create a composition
============================
-Use <ui:composition to define a composition. "template" attribute's value is the full path to the template to be used.
(with .xhtml extension)
-Use a namespace : xmlns:ui="http://java.sun.com/jsf/facelets"
-Inside the composition tag, use <ui:define to override, or replace every <ui:insert you want to customize in the template.

-You can use <ui:include> inside <ui:define to include a composition. "src" is the path to the file with .xhtml extension

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="path_To_Template_File.xhtml">
...
<ui:define name="attribute_name1">
Text that override template's text
</ui:define>
...
<ui:define name="attribute_name2">
<ui:include src="path_To_TheFile_To_Include.xhtml">
</ui:include>
</ui:composition>

Le même article en français 

Read more...

Templates, les modèle en JSF2

English Version

Templates ou modèles est la possibilité d'utiliser une interface commune pour afficher d'une façon similaire plusieurs pages ou views dans votre site JSF2.

Si on souhaite avoir, par exemple une identité unique d'un site Web, en gardant la même présentation à travers toutes les pages, on a tout intérêts à utiliser des modèles en JSF2. L'avantage de cette méthode par rapport aux feuilles de style est de répéter l'ensemble ou une partie de la structure d'un document. Gardez des liens par exemple dans toutes les pages.

Commençons par un petit exemple. Une structure contenant en-tête, partie de navigation et un corps.

Utiliser le système de templates ou modèles est composé de deux parties :

  • Créer le modèle ou l'interface
  • Utiliser le modèle en créant des compositions


jsf_style.css
<!--
/* En-Tête */
  #masthead {
    position:relative;
    padding:10px;
    background-color:#FFF;
    height: 50px;
    border: 1px #000 solid;
    margin-right:18%;
     }

/********************************************************************************
Sidebar
*******************************************************************************/
/* Navigation et liens */
  #sidebar {
    float:left;
    padding:12px;
    width:14%;
     background-color:#fcb968; 
    border: 1px #c0c0c0 solid;
     }

/********************************************************************************
Content
*******************************************************************************/      
    /* Contenu */
  #content {
    position:relative;
    margin-left:16%;
    margin-right:18%;
    padding:12px;
    border: 2px #fcb968 solid;
     }
-->

layout.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK REL="StyleSheet" HREF="stylesheets/jsf_style.css" TYPE="text/css" />

<title>Using templates in JSF 2</title>
</head>
<body>
<!-- +++++++++++++++++++++++++++++++++MASTHEAD+++++++++++++++++++++++++++-->
<div id="masthead">
<h1 align="center">Using templates in JSF 2</h1>
</div>
  
<!-- +++++++++++++++++++++++++++ SIDEBAR AND LINKS +++++++++++++++++++++++++ -->
<div id="sidebar">
<p><a href="#">Formations</a></p>

<p><a href="#">Testing</a></p>

<p><a href="#">JSF 2</a></p>

</div>

<!-- +++++++++++++++++++++++++CONTENT++++++++++++++++++++++++++++++++++++++++ -->

<div id="content">
<p>Line1</p>
<p>Line2</p>
<p>Line3</p>
</div>  
</body>
</html>

Affichage


Pour créer un modèle (template)
  • Ajouter une instruction " namespace "
        xmlns:ui="http://java.sun.com/jsf/facelets"

  • Pour chaque emplacement qu'on désire personnaliser dans le modèle, on insère une instruction "ui:insert", avec ou sans corps. Avec corps, si on souhaite avoir un comportement ou texte par défaut. L'instruction <ui:insert est couplée avec une instruction <ui:define dans les parties utilisatrices du modèle (compositions)
Example :
Nous allons utiliser le fichier " layout.xhtml " comme modèle et personnaliser l'en-tête dans chaque page utilisatrice de ce modèle :

  • Ajouter <ui:insert avec corps pour chaque partie à personnaliser dans le modèle, chaque <ui:insert est identifie par un attribut " name ". Cela sert à remplacer le contenu de <ui:insert dans les compositions en utilisant le même " name " dans <ui:define.

         <h1 align="center">
        <ui:insert name="header">
        Using templates in JSF 2
        </ui:insert>
        </h1>

  • Créer une composition (une page xhtml ordinaire, qui va utiliser le même modèle " layout.xhtml ", en personnalisant une partie (en-tête) définie par <ui:insert name="header"
layout.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
    
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK REL="StyleSheet" HREF="stylesheets/jsf_style.css" TYPE="text/css" />

<title>
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</title>
</head>
<body>
<!-- +++++++++++++++++++MASTHEAD++++++++++++++++++++++++++++++++++++++++++++ -->
<div id="masthead">

<h1 align="center">
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</h1>

</div>
  
<!-- +++++++++++++++++++SIDEBAR AND LINKS ++++++++++++++++++++++++++++++++++ -->
<div id="sidebar">
<p><a href="formation.jsf">Formations</a></p>

<p><a href="#">Testing</a></p>

<p><a href="#">JSF 2</a></p>

</div>

<!-- ++++++++++++++++++++++CONTENT++++++++++++++++++++++++++++++++++++++++++ -->

<div id="content">
<p>Line1</p>
<p>Line2</p>
<p>Line3</p>
</div>  
</body>
</html>
formation.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Formation in JSF 2 (Learning)
</ui:define>
</ui:composition>

Note:
Les parties non personnalisées dans "layout.xhtml" restent inchangées.
Remarquer le message affiché par <title> dans le navigateur et l'en-tête

Affichage

testing.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Testing
</ui:define>
</ui:composition>


Affichage

index.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">

</ui:composition>

Affichage

Pas d'affichage par défaut
On utilise <ui:insert sans corps <ui:insert name= "... " />
Example

layout.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
    
      >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK REL="StyleSheet" HREF="stylesheets/jsf_style.css" TYPE="text/css" />

<title>
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</title>
</head>
<body>
<!-- +++++++++++++++++++++MASTHEAD++++++++++++++++++++++++++++++++++++++ -->
<div id="masthead">

<h1 align="center">
<ui:insert name="header">
Using templates in JSF 2
</ui:insert>
</h1>

</div>
  
<!-- ++++++++++++++SIDEBAR AND LINKS +++++++++++++++++++++++++++++++++++++++ -->
<div id="sidebar">
<p><a href="formation.jsf">Formations</a></p>

<p><a href="#">Testing</a></p>

<p><a href="#">JSF 2</a></p>

</div>

<!-- +++++++++++++++++++++++CONTENT++++++++++++++++++++++++++++++++++++++++ -->

<div id="content">
<ui:insert name="content" />
</div>  
</body>
</html>

testing.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Testing
</ui:define>
<ui:define name="content">
<p>Line1 in Testing</p>
<p>Line2 in Testing</p>
<p>Line3 in Testing</p>
</ui:define>
</ui:composition>

Affichage


formation.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
Formation in JSF 2 (Learning)
</ui:define>
<ui:define name="content">
<ol>
<li>Line1 in Testing</li>
<li>Line2 in Testing</li>
<li>Line3 in Testing</li>
</ol>
</ui:define>
</ui:composition>

Affichage


Comment créer une composition
  • L'instruction définie le corps d'une composition <ui:composition. L'attribut "template" sert à indiquer le chemin complet vers le modèle ou template " layout.xhtml "

        <ui:composition xmlns="http://www.w3.org/1999/xhtml"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        template="layout.xhtml">
         ...
         ...
       </ui:composition>

  • A l'intérieur de <ui:composition, on utilise  <ui:define pour chaque <ui:insert qu'on désire personnaliser dans le modèle

        <ui:composition>
        ...
       <ui:define name="header">
      Testing
      </ui:define>
      ...
      </ui:composition>

Pour aller plus loin, utiliser  <ui:include
Il est possible d'utiliser un fichier et l'importer dans une instruction <ui:define, de cette manière, on peut insérer dans cette partie un logo, un texte, etc.. et l'utiliser dans plusieurs autres fichiers ou compositions.


Example :
formation.xhtml and testing.xhtml vont utiliser  un fichier de personnalisation "header.xhtml".

Note:
Le fichier à importer en utilisant <ui:include est un fichier .xhtml
<title> n'est plus utilisé dans l'exemple

header.xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">

<h:graphicImage url="images/logo.gif" width="100px" />
<br/>
<h:outputText value="http://www.java-javafx.com"/>

</ui:composition>

formation.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
<ui:include src="header.xhtml">
</ui:include>
<br/>
Formation in JSF 2 (Learning)
</ui:define>
<ui:define name="content">
<ol>
<li>Line1 in Testing</li>
<li>Line2 in Testing</li>
<li>Line3 in Testing</li>
</ol>
</ui:define>
</ui:composition>

testing.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="layout.xhtml">
<ui:define name="header">
<ui:include src="header.xhtml">
</ui:include>
<br/>
Testing
</ui:define>
<ui:define name="content">
<p>Line1 in Testing</p>
<p>Line2 in Testing</p>
<p>Line3 in Testing</p>
</ui:define>
</ui:composition>

Affichage

Résumé

Pour créer un modèle (template)
===================== =
-Utiliser une instruction " namespace "
 xmlns:ui="http://java.sun.com/jsf/facelets"

-A chaque endroit qu'on désire personnalier dans le modèle on insère "ui:insert" son attribu " name " sert à l'indentier par la suite dans le compositions en utilisant <ui:define. En l'absence d'une instruction <ui:define correspondante à <ui:insert, la valeur par défaut de <ui:insert est utilisée, si <ui:insert dispose d'un corps

<ui:insert name="var1" /> pas de valeur par défaut
ou
<ui:insert name="var2">
Texte par défaut
</ui:insert>

Créer des fichiers utilisateurs (compositions)
============================ =========
-Dans <ui:composition "template" sert à indiquer le chemin complet vers le modèle (template), avec l'extension .xhtml

-<ui:define sert à remplacer ou à redéfinir des <ui:insert de même nom dans le modèle

-On peut utiliser <ui:include> dans <ui:define pour importer un fichier. "src" indique son chemin (extension.xhtml)

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    template="chemin_complet_modele.xhtml">
      ...
      <ui:define name="var1">
    Texte de remplacement
      </ui:define>
      ...
      <ui:define name="var2">
      <ui:include src="chemin_vers_fichier_a_importer.xhtml">
      </ui:include>
      </ui:composition>

English version

Read more...

Drawing Charts on Google App Engine for Java using JSF2 and Google Visualization API

>> 16 November 2010




On Google App Engine, many of the classes used in Java for drawing or displaying images are restricted classes (Not on GAEJ white list). A partial solution is to use Google's dedicated Images service. Another solution is to use for instance another framework for images with permitted classes. Google has an elegant library for visualizing data, like charts among other interesting visualizations. Using this visualization API is pretty straightforward, here is a step by step example

How to use Google Visualization API

  • Begin by loading some Javascript libraries, there are 3 to load.
    1. Google AJAX API
      This library must be loaded first.
      Is used to load other libraries and handle some core functionality such as event handling.
      Defines the google.load() and google.setOnCallback()
      <script type="text/javascript" src="http://www.google.com/jsapi"></script>


    2. Google Visualization API core
      Common classes and methods used to create and handle visualizations (DataTable, query object, error handlers),
      All is in google.visualization namespace.
      Loading this library is combined with the third one.

    3. A library for each type of visualization
      Each one is a specific visualization (for example, a pie chart or a line chart)
      Is a JavaScript class that exposes methods specific to that visualization, plus a few common methods and events (such as draw() and select).
      <script type="text/javascript">
      // Load the Visualization API and the piechart package.
      google.load('visualization', '1', {'packages':['corechart']});

  • Prepare your data.
    specifying the data yourself in code,
    or querying a remote site for data.

  • Create an instance of your visualization.
    Instantiate your visualization by calling its constructor and passing in a reference to your <div> element (see later).

  • Draw your visualization.
    Call draw() on your visualization and pass in your data to draw your visualization on the page.

  • Options.
    There are various other optional actions, such as handling user events or specifying visualization options.

  • Add a <div> to your page.
    This is the visualization area in the page
A simple HTML Example:

<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>


<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});



// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);


// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.

function drawChart() {

// Create our data table.
var data = new google.visualization.DataTable();

//the first col is a String the second is a number
data.addColumn('string', 'Month');
data.addColumn('number', 'Users');

//we pass a 2 dimension array of (string,number)
data.addRows([
['jan', 11],
['feb', 2],
['mar', 12],
['apr', 20],
['jun', 7]
]);




// Instantiate and draw our chart, passing in some options.

var chart = new google.visualization.PieChart(document.getElementById('chart_div'));


//first arg to draw is an instance of DataTable, the second are options

chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Users'});
}
</script>

</head>

<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>

JSF2 combined with Visualization API
First example
A very simple rating, using radio buttons

SiteStatBean (SiteStatBean.java)
package com.java_javafx.ka.visualization;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

/**
* @author Kaesar ALNIJRES
*
*/
@ManagedBean(name="stat")
@SessionScoped

public class SiteStatBean  implements Serializable{
private int good=1;
private int average;
private int bad;
private String rating;
private List<SelectItem> ratingChoices;

/**
* @return the good
*/
public int getGood() {

return good;
}
/**
* @param good the good to set
*/
public void setGood(int good) {
this.good = good;
}
/**
* @return the average
*/
public int getAverage() {
return average;
}
/**
* @param average the average to set
*/
public void setAverage(int average) {
this.average = average;
}
/**
* @return the bad
*/
public int getBad() {

return bad;
}
/**
* @param bad the bad to set
*/
public void setBad(int bad) {
this.bad = bad;
}
/**
* @return the rating
*/
public String getRating() {

return rating;
}
/**
* @param rating the rating to set
*/
public void setRating(String rating) {
String selected=rating;

if(selected.equals("Good"))
good++;
if (selected.equals("Average"))
average++;
if (selected.equals("Bad"))
bad++;

this.rating = rating;
}
/**
* @return the ratingChoices
*/
public List<SelectItem> getRatingChoices() {

ratingChoices=new ArrayList<SelectItem>();
ratingChoices.add(new SelectItem("Good") );
ratingChoices.add(new SelectItem("Average") );
ratingChoices.add(new SelectItem("Bad") );

return ratingChoices;
}
/**
* @param ratingChoices the ratingChoices to set
*/
public void setRatingChoices(List<SelectItem> ratingChoices) {
this.ratingChoices = ratingChoices;
}


}

polling.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Polling</title>
<!-- Using Google Visualization API -->

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">

var loaded=false;
var chart;
var dataTable;
google.load('visualization', '1', {'packages':['corechart']});

google.setOnLoadCallback(drawChart);



// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.

function drawChart() {
loaded=true;

// Create our data table.
dataTable = new google.visualization.DataTable();

//the first col is a String the second is a number
dataTable.addColumn('string', 'Site');
dataTable.addColumn('number', 'Rating');

//we pass a 2 dimension array of (string,number)

dataTable.addRows([
['Good', #{stat.good}],
['Average', #{stat.average}],
['Bad', #{stat.bad}],

]);



// Instantiate and draw our chart, passing in some options.

chart = new google.visualization.PieChart(document.getElementById('polling_div'));


//first arg to draw is an instance of DataTable, the second are options

chart.draw(dataTable, {width: 400, height: 240, is3D: true, title: 'Rating for this site'});

}


</script>
<!-- end visualization api -->
</head>
<body>


<h:form>
<h:panelGrid>

<h:outputText value="What do you think of this site?" />
<div id="polling_div"></div>
<h:selectOneRadio value="#{stat.rating}" id="rating">
<f:ajax render="panel"/>
<f:selectItems value="#{stat.ratingChoices}" />
</h:selectOneRadio>

</h:panelGrid>
</h:form>

<h:panelGrid id="panel">
<script type="text/javascript">
if(loaded)
{
var good=#{stat.good}
var average=#{stat.average}
var bad=#{stat.bad}

dataTable.setValue(0,1,good)
dataTable.setValue(1,1,average)
dataTable.setValue(2,1,bad)

chart.draw(dataTable, {width: 400, height: 240, is3D: true, title: 'Rating for this site'});
}
</script>

</h:panelGrid>


</body>
</html>

Visualization API with JSF2


Example 2
Adding a progress bar (busy bar)
First of all we add a function in JavaScript section, this function will be called when an Ajax event is launched. It received an argument "data", or any other name. The variable "data.status" gives information about the progression of the Ajax request. If this variable's value is "begin",the request is sent and the program is waiting for the response. In this case we display any image to let the user wait. If the variable has any other value like "success" or "complete" the request has ended, so we can hide the busy image and display the chart. Javascript function is a callback function triggered by "onevent" attribute in the Ajax call.

I've added a sleep call, only to simulate long call on the development server

Note:
prependId="false" of the form is used to split components ID from the form's ID. Like this we can the given ids without using the form's associated id.

polling2.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Polling</title>
<!-- Using Google Visualization API -->

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">

var loaded=false;
var chart;
var dataTable;
google.load('visualization', '1', {'packages':['corechart']});

google.setOnLoadCallback(drawChart);



// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.

function drawChart() {
loaded=true;

// Create our data table.
dataTable = new google.visualization.DataTable();

//the first col is a String the second is a number
dataTable.addColumn('string', 'Site');
dataTable.addColumn('number', 'Rating');

//we pass a 2 dimension array of (string,number)

dataTable.addRows([
['Good', #{stat.good}],
['Average', #{stat.average}],
['Bad', #{stat.bad}],

]);



// Instantiate and draw our chart, passing in some options.

chart = new google.visualization.PieChart(document.getElementById('polling_div'));


//first arg to draw is an instance of DataTable, the second are options

chart.draw(dataTable, {width: 400, height: 240, is3D: true, title: 'Rating for this site'});

}
function waiting(data)
{

var status=data.status;
var component = document.getElementById("polling_div");
var progressBar=document.getElementById("progressbar");

if (status == "begin") {
component.style.visibility = "hidden";
progressBar.style.visibility="visible";
}
else {
component.style.visibility = "visible";
progressBar.style.visibility="hidden";

}

}

</script>
<!-- end visualization api -->
</head>
<body>


<h:form prependId="false">
<h:panelGrid>


<h:outputText value="What do you think of this site?" />
<h:panelGroup>
<h:graphicImage id="progressbar" url="/images/load.gif" style="visibility:hidden"/>
<div id="polling_div"></div>
</h:panelGroup>
<h:selectOneRadio value="#{stat.rating}" id="rating">
<f:ajax render="panel" onevent="waiting"/>
<f:selectItems value="#{stat.ratingChoices}" />
</h:selectOneRadio>

</h:panelGrid>
</h:form>

<h:panelGrid id="panel">
<script type="text/javascript">
if(loaded)
{
var good=#{stat.good}
var average=#{stat.average}
var bad=#{stat.bad}

dataTable.setValue(0,1,good)
dataTable.setValue(1,1,average)
dataTable.setValue(2,1,bad)

chart.draw(dataTable, {width: 400, height: 240, is3D: true, title: 'Rating for this site'});
}
</script>

</h:panelGrid>


</body>
</html>

MangedBean (SiteStatBean.java)

package com.java_javafx.ka.visualization;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

/**
* @author Kaesar ALNIJRES
*
*/
@ManagedBean(name="stat")
@SessionScoped

public class SiteStatBean  implements Serializable{
private int good=1;
private int average;
private int bad;
private String rating;
private List<SelectItem> ratingChoices;

/**
* @return the good
*/
public int getGood() {

return good;
}
/**
* @param good the good to set
*/
public void setGood(int good) {
this.good = good;
}
/**
* @return the average
*/
public int getAverage() {
return average;
}
/**
* @param average the average to set
*/
public void setAverage(int average) {
this.average = average;
}
/**
* @return the bad
*/
public int getBad() {

return bad;
}
/**
* @param bad the bad to set
*/
public void setBad(int bad) {
this.bad = bad;
}
/**
* @return the rating
*/
public String getRating() {

return rating;
}
/**
* @param rating the rating to set
*/
public void setRating(String rating) {
String selected=rating;

if(selected.equals("Good"))
good++;
if (selected.equals("Average"))
average++;
if (selected.equals("Bad"))
bad++;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.rating = rating;
}
/**
* @return the ratingChoices
*/
public List<SelectItem> getRatingChoices() {

ratingChoices=new ArrayList<SelectItem>();
ratingChoices.add(new SelectItem("Good") );
ratingChoices.add(new SelectItem("Average") );
ratingChoices.add(new SelectItem("Bad") );

return ratingChoices;
}
/**
* @param ratingChoices the ratingChoices to set
*/
public void setRatingChoices(List<SelectItem> ratingChoices) {
this.ratingChoices = ratingChoices;
}


}



Ajax request began.Waiting

Ajax request has finished

Example 3
Persist our data
To persist the data, I'll use some JDO annotations in the ManagedBean to persist and retrieve data from the Datastore. A method "init" annotated "@PostConstruct" is called only once, after the construction of the bean's object. PMF is a singleton used to get a PersistenceManagerFactory instance. A better example for persisting would be for instance to add a button and verify the user's IP, instead of persisting and updating as a response to selecting <h:selectOneRadio.

PMF.java
package com.java_javafx.ka.visualization;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");

private PMF() {}

public static PersistenceManagerFactory get() {
return pmfInstance;
}
}

ManagedBean(SiteStatBean.java)

package com.java_javafx.visualization;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.annotations.*;
import com.google.appengine.api.datastore.Key;
/**
 * @author Kaesar ALNIJRES
 *
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
@ManagedBean(name="stat")
@SessionScoped

public class SiteStatBean implements Serializable{
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
@Persistent
private int good;
@Persistent
private int average;
@Persistent
private int bad;

@NotPersistent
private String rating;
@NotPersistent
private List ratingChoices;


@NotPersistent
private boolean alreadyPersisted;

@NotPersistent
private static final Logger logger=Logger.getLogger(SiteStatBean.class.getName());

@NotPersistent
PersistenceManagerFactory pmf=null;
/**
 * @return the key
 */
public Key getKey() {
    return key;
}
/**
 * @param key the key to set
 */
public void setKey(Key key) {
    this.key = key;
}
/**
 * @return the good
 */
public int getGood() {
   
    return good;
}
/**
 * @param good the good to set
 */
public void setGood(int good) {
    this.good = good;
}
/**
 * @return the average
 */
public int getAverage() {
    return average;
}
/**
 * @param average the average to set
 */
public void setAverage(int average) {
    this.average = average;
}
/**
 * @return the bad
 */
public int getBad() {
   
    return bad;
}
/**
 * @param bad the bad to set
 */
public void setBad(int bad) {
    this.bad = bad;
}
/**
 * @return the rating
 */
public String getRating() {
   
    return rating;
}
/**
 * @param rating the rating to set
 */
public void setRating(String rating) {
    String selected=rating;
    if(selected.equals("Good"))
        good++;
    if (selected.equals("Average"))
        average++;
    if (selected.equals("Bad"))
        bad++;
   
    PersistenceManager pm=null;
    try {
        if(pmf != null)
        {
        pm=pmf.getPersistenceManager();
       
        if(!alreadyPersisted)
        pm.makePersistent(this);
       
        else
        {
            List stats = null;
            stats=(List) pm.newQuery("select from " + SiteStatBean.class.getName()).execute();
            if(stats!=null && !stats.isEmpty())
            {
               
                for(SiteStatBean st:stats)
                {
                        st.setGood(good);
                        st.setAverage(average);
                        st.setBad(bad);
                    }
            }   
        }
       
        }
    } catch (Exception e) {
        // TODO: handle exception
        logger.severe("exception "+e.getMessage());
    }
    finally
    {
        if(pm != null && !pm.isClosed())
            {
            pm.close();
            pm=null;
            }
    }
    this.rating = rating;
}
/**
 * @return the ratingChoices
 */
public List getRatingChoices() {
   
    ratingChoices=new ArrayList();
    ratingChoices.add(new SelectItem("Good") );
    ratingChoices.add(new SelectItem("Average") );
    ratingChoices.add(new SelectItem("Bad") );
   
    return ratingChoices;
}
/**
 * @param ratingChoices the ratingChoices to set
 */
public void setRatingChoices(List ratingChoices) {
    this.ratingChoices = ratingChoices;
}

@PostConstruct
public  void init() {
// initialization code
       
    PersistenceManager pm=null;
    try {
        pmf = PMF.get();
        pm=pmf.getPersistenceManager();
       
        List stats = null;
        stats=(List) pm.newQuery("select from " + SiteStatBean.class.getName()).execute();
        if(stats!=null && !stats.isEmpty())
        {
            alreadyPersisted=true;
            for(SiteStatBean st:stats)
            {
                good+=st.getGood();
                average+=st.getAverage();
                bad+=st.getBad();
            }
           
        }
    } catch (Exception e) {
        // TODO: handle exception
        logger.severe("Exception "+e.getMessage());
    }
    finally
    {
        if(pm != null && !pm.isClosed())
            {
            pm.close();
            pm=null;
            }
    }
    //The chart will refuse to be drawn if all are 0
  //so put 1 in all
    if(good==0 && average==0 && bad==0)
     {good=1;
     average=1;
     bad=1;
     }
}
}


Read more...

Have you tried StopDuplicates?

>> 21 October 2010

StopDuplicates is a Java Graphical application that l released to Free/Open Source some years ago (last update was on march 2009).

This program can  easily locate and remove duplicates, based on MD5sums.

It's available in English, French and Spanish.

All  you need is the .jar file and JDK installed on your machine (platform independent)

You can download program and source files

Enjoy !

http://apps.java-javafx.com/download.jsp

Read more...

Hello World, Barcode in Java, using ZXing

>> 29 September 2010

I have posted an article about using "Barbecue" for generating bar codes in Java, a few days ago.

 Yesterday I read this excellent post : about using "ZXing" Java Library (Open Source), to generate bar code in Java programs.

This library looks very interesting and powerful. Here is a Hello World.

ZXing ("Zebra Crossing")

The description is from the library's site
"ZXing (pronounced "zebra crossing") is an open-source, multi-format 1D/2D barcode image processing library implemented in Java. Our focus is on using the built-in camera on mobile phones to photograph and decode barcodes on the device, without communicating with a server."

Project's Site :
http://code.google.com/p/zxing/

Installing
  • Download the current version (Zxing-1.6.zip)
  • Unzip in a folder of your choice, this will give "zxing-1.6" folder
  • For normal Java programs, two .jar files must be built
  • One of the possibilities is to use "ant"
  • cd zxing-1.6/core
  • Type "ant" you'll get in the same folder "core.jar"
  • cd zxing-1.6/javase
  • Type "ant" you'll get here "javase.jar"
  • In your Java project, create a folder (give it any name), for instance "lib"
  • Copy "core.jar" and "javase.jar" to YourProject/lib
  • Add these two .jar files to YourProject/properties/Java Build Path



Hello World

package com.java_javafx.ka;

import java.io.File;
import java.io.FileOutputStream;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;

/**
 *
 * @author Kaesar ALNIJRES
 *
 */
public class HelloWorld {

  
    public static void main(String[] args) {
      
           int width = 440;
           int height = 48;
           
             
           BitMatrix bitMatrix;
        try {
            bitMatrix = new Code128Writer().encode("Hello World !!!",BarcodeFormat.CODE_128,width,height,null);
            MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(new File("/home/kas/zxing_barcode.png")));
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}


Read more...

PrimeFaces with JSF2 Fist Step

>> 27 September 2010


JSF2 is a very cool technology. With PrimeFaces, you can add lots of components, themes and goodies, with almost no efforts at all.

Welcome to PrimeFaces
"PrimeFaces is a lightweight open source component suite for Java Server Faces 2.0 featuring 100+ rich set of JSF components."

Getting started
1.Download the .jar (current is primefaces-2.2.M1.jar). Add it to  WEB-INF/lib

2.Add WEB-INF/lib/primefaces-2.2.M1.jar to YourProject/properties/Java Build Path

3.Import the namespace, by instruction in .xhtml page
"xmlns:p="http://primefaces.prime.com.tr/ui"

Web Site :
http://www.primefaces.org/

Will it play on GAEJ
Yes. Except for some special operations where other libraries are used. Some of these use dependencies that are not on the "The JRE Class White List" of Google, for instance Jcomponent when generating bar  code with "Barbecue".
Hello Calendar
To change a bit of the famous "Hello World", I'll try here a calendar (one of the components provided by PrimeFaces)

faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
 version="2.0">

 <navigation-rule>
 <from-view-id>/prime.xhtml</from-view-id>
 <navigation-case>
 <from-outcome>done</from-outcome>
 <to-view-id>/result.xhtml</to-view-id>

  </navigation-case>
 
  </navigation-rule>
 </faces-config>


PrimeTest.java (The bean)
package fr.iipt.ka.faces;


import java.util.Date;


import javax.faces.bean.*;

@ManagedBean(name="pTest")
@RequestScoped
public class PrimeTest {
  
    private Date date;
        /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    /**
     * @param date the date to set
     */
    public void setDate(Date date) {
      
        this.date = date;
    }
  
    public String whatNext()
    {
        return "done";
    }
  

}

prime.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
<p:calendar value="#{pTest.date}" mode="popup" showOn="button" pattern="dd/MM/yyyy"/>
<h:commandButton action="#{pTest.whatNext}" value="result"/>
</h:panelGrid>
</h:form>
</h:body>
</html>

result.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>result.xhtml</title>
</h:head>
<h:body>

result.xhtml<br/>
<h:outputText value="#{pTest.date}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:outputText>

</h:body>
</html>








 

Using a customized theme
There are many themes, ready to use. Each is a zip file to download on PrimeFaces site. When unzipped, it creates one folder "images" and a css file "skin.css"

How to install
1.Disable default skin
in web.xml
<!-- Disable original theme in primefaces -->
   <context-param>
      <param-name>primefaces.skin</param-name>
        <param-value>none</param-value>
    </context-param>
<!--END Disable original theme in primefaces  -->

2.Unzip the downloaded theme file (zip) into a folder in your application (I Used in the example "ui-lightness" the full path  to the unzipped folder is "war/primeFacesThemes/ui-lightness/")
3.In any .xhtml put a link to the css file
 <link type="text/css" rel="stylesheet" href="primeFacesThemes/ui-lightness/skin.css" />

web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  
  
    <context-param>
    <param-name>org.apache.myfaces.config.annotation.LifecycleProvider</param-name>
    <param-value>org.apache.myfaces.config.annotation.NoInjectionAnnotationLifecycleProvider</param-value>
  </context-param>
 
  <!-- for EL 2.2 -->
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>

 <!-- end EL 2.2 -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
<!--  end add -->




<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>

<!-- Disable original theme in primefaces -->
   <context-param>
      <param-name>primefaces.skin</param-name>
        <param-value>none</param-value>
    </context-param>
<!-- END Disable original theme in primefaces  -->
  
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

prime.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
>
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Calendar in PrimeFaces</title>
<link type="text/css" rel="stylesheet" href="primeFacesThemes/ui-lightness/skin.css" />
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
<p:calendar value="#{pTest.date}" mode="popup" showOn="button" pattern="dd/MM/yyyy"/>
<h:commandButton action="#{pTest.whatNext}" value="result"/>
</h:panelGrid>
</h:form>
</h:body>
</html>



Read more...

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP