Facelets
Facelets is a design/layout framework really easy to use and configure. Unfortunately, the lack of good tutorials over the internet, gabe me the idea to write this post to explain how to configure it and use it.
If you are building a JSF application, then Facelets is the perfect match for your layout configuration (although Facelets is independent of the languge and can be used almost anywhere). Facelets is to JSF what Tiles is to Struts.
Facelets properties
- Easy components composition.
- Logic labels creation.
- Expression functions.
- Friendly development for the graphic designero.
- Component libraries creation.
Basically you will have to add some configuration to your web.xml file, modify you .jsp extentions to .xhtml (or .xjsp), create the layout and learn how to use it.
1 – Download and install all the necesary files into your claspath. You wil have to download the jsf-facelets.jar. Refer to Faces Developer Center to download it.
2 - Configure the web.xml. The first parameter tells Facelets which suffix will your pages have, and the second will let you see a console debug. Add these lines to your web.xml:
Facelets es un framework de diseño de páginas muy facil de usar y configurar. La falta de buenos tutoriales en internet, me dio la idea para escribir este post y explicar cómo configurarlo y usarlo.
Si estás contruyendo una aplicación con JSF, entonces Facelets es el agregado ideal para la configuración del “layout” (aunque Facelets es independiente del lenuguaje y puede ser usado en cualquier tipo de aplicación). Facelets es para JSF lo que Tiles es para Struts.
Propiedades de Facelets
- Trabajo basado en plantillas.
- Fácil composición de componentes.
- Creación de etiquetas lógicas a la medida.
- Funciones para expresiones.
- Desarrollo amigable para el diseñador gráfico.
- Creación de librerías de componentes.
Básicamente, se deberá agregar configuración al archivo web.xml, modificar sus extensiones .jsp a .xhtml (or .xjsp), crear el “layout” y aprender cómo usarlo.
1 – Descarguen e installen todos los archivos necesarios a su classpath. Deberán descargar el archivo jsf-facelets.jar. Dirigirse a Centro de desarrollo de JSF para bajarlo.
2 - Configurar el archivo web.xml. El primer paámetro le dice a Facelets qué sufijo tendrán las páginas, y el segundo va a permitir ver el debug en la consola. Agregar estas líneas al web.xml:
1 2 3 4 5 6 7 8 | <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param> <context-param> <param-name>facelets.DEVELOPMENT</param-name> <param-value>true</param-value> </context-param> |
3 – Define a layout. Create a layout.xhtml and the included pages of the layout (footer.xhtml, header.xhtml and navigation.xhtml, for example).
3 – Definir un “layout”. Crear un archivo layout.xhtml y las páginas que serán incluidas (por ejemplo footer.xhtml, header.xhtml and navigation.xhtml).
layout.xhtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!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:ui="http://java.sun.com/jsf/facelets"> <body> <div> <div> <ui:include src="header.xhtml" /> </div> <div> <ui:include src="navigation.xhtml" /> </div> <div> <ui:insert name="body"> Default Content </ui:insert> </div> <div> <ui:include src="footer.xhtml" /> </div> </div> </body> </html> |
Then difine the pages that are in the layout: footer.xhtml, header.xhtml and navigation.xhtml. I will put one of these as an example.
Después definir las páginas que están en el layout: footer.xhtml, header.xhtml and navigation.xhtml. Voy a poner una de las mismas como ejemplo.
header.xhtml
1 2 3 4 5 6 7 8 9 10 11 12 | <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xml:lang="en" lang="en"> <body> <p> HEADER </p> </body> </html> |
4 – Rename files. Rename any file you haven’t in your Navigation Rules in the faces-congif.xml file to “.xhtml”.
5 – Use your configuration. Now all the configurarion is done, you have to try it. The only difference now with your old JSF files is that you don`t longer use the f:view to begin your JSF code. You will have to use ui:composition to tell Facelets wich layout this page will apply to and ui:define name=”body” to insert in your template the code inside the tag.
4 – Renombrar archivos. Renombrar todos los archivos en las Navigation Rules en el archivo faces-congif.xml a “.xhtml”.
5 – Usar la confiuguración. Ahora que la configuración está terminada, hay que probarla. La única diferencia con los archivos viejos de JSF es que ahora no hay que usar mas el tag f:view al empezar a escribir código JSF. Ahora hay que aplicar ui:composition para decirle a Facelets a qué layout se aplicará la página y ui:define name=”body” para instertar en el template el código dentro del tag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <body> <ui:composition template="layout.xhtml"> <ui:define name="body"> <h:form> <h:panelGrid columns="2"> <h:outputLabel value="User Name:"/> <h:outputLabel id="username" value="#{UserBean.userName}"></h:outputLabel> </h:panelGrid> <h:commandButton value="Back to list" rendered="true" action="#{UserBean.listUsers}" id="submit" /> </h:form> </ui:define> </ui:composition> </body> </html> |
By defining ui:define name=”body”, we tell Facelets to insert in the tag named “body” of the layout page all the code of the tag. Notice that the f:view is gone and replaced by the ui:composition tag.
Definiendo ui:define name=”body”, le decimos a Facelets que inserte en el tag llamado “body” de la página del layout, todo el código del tag. Observar que f:view ya no está mas y fue reemplazado por el tag ui:composition.

LOVE your blog, thanks for entertaining me
Hope there will be more posts soon
regards, terry
ps – sorry im not that good in writing in english because I came from europe – but i understand a lot
Hola!
Sabes si hay alguna forma de guardar los archivos .xhtml de facelets dentro del WEB-INF?
En lugar de tener todos los archivos sueltos en el directorio de la aplicacion, donde son accesibles desde el navegador, creo que sería mejor tenerlos dentro de un directorio del WEB-INF…
Un saludo!
Hola, si los ponés en WEB-INF funciona todo exactamente igual, sólo tenes que cambiar las referencias.
Saludos
En primer lugar me parece muy bueno la informacion que se ha puesto en esta web. Solamente tengo una duda y es respecto a las reglas de navegacion. Podrias poner un ejemplo sencillo de como deberian quedar en el caso de dar click en una opcion del menu y que solamente refresque la parte del body. Muchas gracias de antemano
Que tal Daniel?
Mirá yo puse en el header links directamente a otras paginas.
Ej: en jsf tags obviamente.
y la pagina page1.xhtml simplemente tiene una configuración similar a la del ejemplo del post (paso número 5).
Espero que te funcione.
Saludos!!
Me parece buena pagina siempre che
hola amigo, con tu post he entendido mucho sobre facelets, pero solo me queda una duda, porque utilizas xhtml? no podes hacer todo eso igual con jspf, o con jsf? o el procesamiento es mas rapido asi ? gracias amigo, espero que me aclare las dudas gracias.
Hola rjpunisher,
Usamos archivos xhtml solo para el ejemplo, pero puedes tener la extensión que mas te guste, como jspf o jsf.
Saludos!