samedi 15 juin 2013

JSF and AJAX : a happy wedding if you understand IDs management

JSF 2 brings AJAX support to a high level of productivity for server side development; but you have to understand some subtle mechanics to really enjoy it.

One of this mechanic is IDs management.

About IDs

IDs, like their names tell us, allow to identify components in the view.

Each component is in the view at a certain place, the whole is a tree of components.

Every ID must be unique.

When doing AJAX with JSF you have to use IDs for source of the request and target of the request.

Use case

Here is a sample page :

Loading ....

I want to refresh 3 areas when my AJAX request complete :
- output inside the  main form
- output2
- output3 inside a second form

Like an UNIX filesystem

Everything is in the ":" usage.

So what means the ":" char ?

The key is to consider it like the slah char in UNIX filesystem.

Component are like files, some are directories : they contain other components.
Some directories are special, they have an influence on client IDs computation.

These special components are  naming container, they give their IDs to their children as a prefix.

So if you inspect XHTML you can see mainform or secondform prefix on some children nodes.

When an AJAX request is running, the current context for ID computation is the nearest naming container in the hierarchy.

All IDs used in ajax tag without a ":" are evaluated from this starting point. This is the current directory.

The solution

In sample above, my AJAX tag must use the following IDs :

Loading ....


1) What is the nearest naming container ?

It's mainform.

2) What is the relationship between output and mainform ?

output is a child node, I can target it directly and relatively:

./output -> output

3) What is the relationship between output2 and mainform ?

It's not in mainform, I must target it through the root of the tree, like I do with a filesystem :

/output2 -> :output2

4) What is the relationship between output3 and mainform ?

It's not in mainform, I must target it through the root of the tree but it's in secondform "directory" :

 /secondform/output3 -> :secondform:output3

Few tags are naming container :
- data
- form

But all composite components you create or use are naming containers !

Be careful when using these, they have a serious impact on how you have to write IDs in AJAX tags.

So, enjoy using both JSF and AJAX !

Contrat Creative Commons
the jee architect cookbook by Olivier SCHMITT est mis à disposition selon les termes de la licence Creative Commons Paternité - Pas d'Utilisation Commerciale - Pas de Modification 3.0 Unported.

1 commentaire: