Wednesday, May 23, 2012

JSF - Facelets

Facelets is a 'templating' technology for JSF - it allows us to:
  • Write XHTML files
  • Use JSF EL expressions to call methods on JSF Beans
  • Divide and Rule - compose pages from smaller XHTML pages
  • Use JSF Rich components 
We already saw the first two, now lets see how to compose pages from smaller XHTML pages.

This feature is very similar to Apache Tiles framework that we saw earlier in this post.

Let us suppose that we will need to create several pages with the same layout, but different content.

In your /src/main/webapp folder, create a folder 'template'

In /src/main/wepapp/template, create a file template.xhtml, like this:
 <!DOCTYPE html>  
 <html xmlns="http://www.w3.org/1999/xhtml"  
      xmlns:h="http://java.sun.com/jsf/html"  
      xmlns:f="http://java.sun.com/jsf/core"  
      xmlns:ui="http://java.sun.com/jsf/facelets">  
   
      <h:head>  
           <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
           <title><ui:insert name="title">Default Title</ui:insert></title>  
      </h:head>  
   
      <h:body>  
           <h3>Basic Java Series</h3>  
           <ui:insert name="content">Default content</ui:insert>  
           <p>Visit us at www.projectconfucius.org</p>  
      </h:body>  
 </html>  
   

Notice that we have included the facelets tag library, under the name space 'ui'.

All our pages can use this template which automatically generates a header ("Basic Java Series") and footer ("Visit us..").

Each page can define its own title and content. We use the ui:insert tag to specify points at which a child XHTML page can insert its own content.

Let us update greet.xhtml to use this template, like this:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 <html xmlns="http://www.w3.org/1999/xhtml"  
      xmlns:h="http://java.sun.com/jsf/html"  
      xmlns:f="http://java.sun.com/jsf/core"  
      xmlns:ui="http://java.sun.com/jsf/facelets">  
   
       <ui:composition template="/templates/template.xhtml">  
   
           <ui:define name="title">JSF</ui:define>  
   
           <ui:define name="content">  
                <h1>#{helloBean.greeting}</h1>  
           </ui:define>  
   
   </ui:composition>  
 </html>  

We are using the ui:define tag to insert a title and content into the template.

If you now build and deploy HelloWorldJSF, and point your browser to:
http://localhost:8080/HelloWorldJSF/

you will see "Hello World, JSF!"  printed between the header and footer.
Notice also that the page title is now "JSF".

No comments: