JSF Tutorial: How to use ui:include and ui:fragment with Parameters

Most of developers are not as concerned about code organization in the front-end as they are in the back-end, it’s much easier to find duplicated code in a JSF page than it is in a Java class, making it a lot harder and time consuming for the developer to maintain the pages.

To solve that problem we have to treat blocks of JSF code as functions, let’s take a look at the code bellow as an example:

<h:form>
   <div class="form-group">
      <h:outputLabel styleClass="col-sm-2 control-label" value="First Name"/>
      <h:inputText styleClass="form-control col-sm-2" value="#{testMbean.name}"/>
   </div>
   <div class="form-group">
      <h:outputLabel styleClass="col-sm-2 control-label" value="Last Name"/>
      <h:inputText styleClass="form-control col-sm-2" value="#{testMbean.lastName}"/>
   </div>
   ...
</h:form>

Here we have a form with multiple fields that look exactly the same, the only difference is the label and the input value, if this form was a Java class we would certainly create a method receiving these two attributes, but as we are in a JSF page our best option is to create a ui:fragment containing a single field:

field.xhtml

<ui:fragment xmlns="http://www.w3.org/1999/xhtml"
             xmlns:h="http://xmlns.jcp.org/jsf/html"
             xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
 
    <div class="form-group">
        <h:outputLabel styleClass="col-sm-2 control-label" value="#{label}"/>
        <h:inputText styleClass="form-control col-sm-2" value="#{value}"/>
    </div>
</ui:fragment>

Note that now I’m using the variables #{label} and #{value}, so every time I include this fragment I have to pass these parameters.

When using the fragment our form looks like this:

<h:form>
   <ui:include src="field.xhtml">
      <ui:param name="label" value="Name"/>
      <ui:param name="value" value="#{testMbean.name}"/>
   </ui:include>
   <ui:include src="field.xhtml">
      <ui:param name="label" value="Last Name"/>
      <ui:param name="value" value="#{testMbean.lastName}"/>
   </ui:include>
   ...
</h:form>

It doesn’t seen much of an advantage to use fragments, but imagine if you had to add a style class to your input, it would be much easier to add it only in the fragment instead of having to find every input on your project and add the class to each one of them one by one.