A photo of Geoffrey Hayward

How to Store Variables in JSF Facelets

Published September 7, 2015

JSF Facelets can store the returned value yielded from a call to an EJB. Doing so will mean the EJB does less work.

Let’s say you are implementing a Facelet that will display a message stating something like ‘No results’ when a collection is empty. If the collection is not empty, the Facelet will call the EJB a second time. First to calculate the size of the collection; second to display the data in the collection etc.

Here is an example:

    [...]

    <ui:fragment rendered="#{pages.all().size() == 0}" >
        <h:outputText value="No pages yet." />
    </ui:fragment>
                
    <ui:fragment rendered="#{pages.all().size() > 0}" >
        <h:dataTable value="#{pages.all()}" var="page">
            [...]
        </h:dataTable>
    </ui:fragment>

    [...]

In the example above the Facelet calls the EJB three times. First to calculate the size of the collection; second to display the elements the data table will occupy; third the data from the collection.

How to Store Values in JSF Facelets

The calling to the EJB can be reduced to just once per page render. Calling the backing bean using the ui:param JSF element will store the returned value in a variable.

<f:metadata>
   <ui:param name="pageSet" value="#{pages.all()}" />
</f:metadata>

Using the ui:param JSF element, here is an improved example:

    [...]

    <f:metadata>
      <ui:param name="pageSet" value="#{pages.all()}" />
    </f:metadata>

    [...]

    <ui:fragment rendered="#{pageSet.size() == 0}" >
        <h:outputText value="No pages yet." />
    </ui:fragment>
                
    <ui:fragment rendered="#{pageSet.size() > 0}" >
        <h:dataTable value="#{pageSet}" var="page">
            [...]
        </h:dataTable>
    </ui:fragment>

    [...]

I hope this helps.

Related Posts

Illustration of a laptop displaying Java code related to finding the context path with JSF, set against a web development-themed background.

Find the Context Path with JSF

September 22, 2015

Sometimes JSF does not have a component that will produce a particular type of HTML element. That’s not a problem but, I always forget the three method deep route to the context path. I always find I have to work through an IDE’s code completion tool to find the application’s path.

Continue reading