What are Facelets ? In short, Facelets is a part of the JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces technology-based applications. In this sample article we will see a few simple example of this technology.
Facelets is a part of the JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces technology-based applications.
Facelets are generally created as XHTML pages supporting a special set of Tag Libraries.
The biggest advantage of using Facelets for large-scale development projects include the following:
- Support for code reuse through templating and composite components
- Functional extensibility of components and other server-side objects through customization
- Faster compilation time
- Compile-time EL validation
- High-performance rendering
We will best understand the concept with some example. Let's see how Facelets can be used to create templates.
Creating Templates with Facelets:
Facelets emphasizes its ability to template content in your application. Templating promotes re-use and eases long term maintenance of your application, allowing content to be changed in one spot, but used in multiple pages.
When describing templating within Facelets, we have two roles: the template and the template client. A template is basically a document which can act as a template; but what makes a document a template? It just simply uses one or more <ui:insert/> tags to inject some content from another source. The other half of the equation is the template client, which references the template, adding its own customizations.
Here's an a sample template.xhtml:
Two things to notice:
At first the tag library declaration (xmlns:ui="http://java.sun.com/jsf/facelets") which informs the compiler we want to use the tag for templates.
Then, the template tags used. In this sample we are using the ui:include tag to include another .xhtml page in the document. We are using also the ui:insert tag which can be thought as a custom part of the document which will be inserted by the client.
For the purpose of this sample, just include two xhtml files named header.xhtml and footer.xhtml containing an html header text like this:
<h:outputText id="result" value="This is the Facelet Header"/>
Now let's move to the template client (templateClient.xhtml):
The things to notice is the ui:composition tag which tells that we are using the template.xhtml file as a template. Then, we are defining (through the ui:define tag) the content of the "content" section.
That's all. Remember to include in your web.xml declaration the correct mapping for .xhtml pages
The resulting page should look like this:
This is the Facelet header
This is the Facelet footer
In the next tutorial we will show how to create composition components which is a feature available in the release 2.0 of JSF