TOTD #46: Facelets with Java Server Faces 1.2

how-to
Sep 22, 20083 mins

This blog updates TOTD #45 to use Facelets as view technology.

Powerful templating system, re-use and ease-of-development, designer-friendly are the key benefits of Facelets. Facelets are already an integral part of Java Server Faces 2.0. But this blog shows how to use them with JSF 1.2.

  1. Download Facelets from here (or specifically 1.1.14). Facelets Developer Documentation is a comprehensive source of information.
  2. Add “jsf-facelets.jar” from the expanded directory to Project/Libraries as shown:

  3. Change the JSF view documents to “.xhtml” by adding the a new context parameter in “web.xml” as:

        javax.faces.DEFAULT_SUFFIX

        .xhtml

     

    The updated “web.xml” looks like:

  4. Specify Facelets as the ViewHandler of JSF application by adding the following fragment to “faces-config.xml”:

     

        com.sun.facelets.FaceletViewHandler   

     

    The updated document looks like:

  5. Create three new XHTML pages by right-clicking on the project, selecting “New”, “XHTML” and name them as “template”, “welcome” and “result”. This creates “template.xhtml”, “welcome.xhtml” and “result.xhtml” in “Web Pages” folder. 
    1. Replace the generated code in “template.xtml” with the code given here. Change the text “Facelets: What’s your favorite City ?”.
    2. Replace the generated code in “welcome.xhtml” with the code given here. Refactor “welcomeJSF.jsp” such that H1 tag and the associated text goes in and rest of the content goes in . Also change the value of “template” attribute of by removing “/”. The updated page looks like:

    3. Replace the generated code in “result.xhtml” with the code given here. Refactor “result.jsp” such that H1 tag and the associated text goes in and rest of the content goes in . Also add a namespace declaration for “https://java.sun.com/jsf/core“.

      Optionally change the

      associated with the command button to:

                     

                         

                     

       

      The updated page looks like:

  6. Add couple of more navigation rules to “faces-config.xml”:

       

            /welcome.xhtml

           

                submit

                /result.xhtml

           

       

       

            /result.xhtml

           

                back

                /welcome.xhtml

           

       

And that’s it, Facelets-based application is now available at “https://localhost:8080/Cities/faces/welcome.xhtml“. The interaction is exactly similar to as shown in

TOTD #45

and some of the sample images (borrowed from

TOTD #45

) are:

Now this application is using Facelets as the view technology instead of the in-built view definition framework.

Please leave suggestions on other TOTD (Tip Of The Day) that you’d like to see. A complete archive of all tips is available here.

Technorati: totd javaserverfaces facelets netbeans glassfish