Friday, July 13, 2012

Programmatic facelet: resource to component

Facelet is a great way to write your UI layout in xml declaratively. However, in highly dynamically website, you need to control facelet construction programmatically.

This seems silly since the the purpose of the facelet to describe the component layout. If you use programmatic approach, you can program component tree directly. This is not completely true. Facelet has the concept of component, composition and template. I may define a fragment of tree structure as component or template and want to mix them programmatically. I do not need to program everything from scratch.

Leaving fragment.xhtml as a resource gives us the advantage to use ResourceHandler to find the file. If it is not a resource, we need to find the URL for this file. We could do it like thisnew File(FacesContext.getCurrentInstance().getExternalContext().getRealPath(PATH) ).toURI().toURL();
Once we have the URL for the fragment file, we can create a facelet from it using FaceletFactory. The created facelet can then be converted to UIComponent.