Building User Interfaces with JSF: Declarative vs. Programmatic Approach

When we are using JSF tags to build the user interface, we are using the declarative approach. With declarative approach we can visualize the hierarchy of the user interface.

Let’s see how it’s possible to produce the same user interface using both approaches. We will build the following simple panel:


Here is an example of declarative approach:

     <h:outputText value="I love New York"/>
  <h:outputText value="I love the Big Apple and using RichFaces"/>

Using tags mimics better how the actual user interface will look. In other words, it’s easier to build the user interface using tags.

Here is an example of programmatic approach that produces exactly the same page:

Application application = FacesContext.getCurrentInstance().getApplication();
// create rich:panel
HtmlPanel panel = (HtmlPanel)application.createComponent(HtmlPanel.COMPONENT_FAMILY);
// set width
// create h:outpuText
HtmlOutputText outputTextHeader = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);
// set h:outputText value
outputTextHeader.setValue("I love New York");
// add header facet to rich:panel
panel.getFacets().put("header", outputTextHeader);
// create h:outputText
HtmlOutputText outputText = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);
// set h:outputText value
outputText.setValue("I love the Big Apple and using RichFaces");
// add h:outputText as a child to rich:panel

As you can probably see, when using programmatic approach, it’s more difficult to visualize and understand the hierarchy of the user interface. It basically looks flat.

While most of JSF pages will be built using the declarative style, programmatic approach will almost always be required in a large application. In situations where pages are highly dynamic, the programmatic approach provides power and flexibility. The programmatic approach is also needed when components need to be manipulated inside a Java class (for example managed beans). A common example of this would be using the ‘binding’ attribute and setting some property of the component, for example:


The programmatic approach is not “bad� as long as you know how and when to use it.

This is just to give you an idea what is the difference between declarative and programmatic approaches to developing user interfaces. Of course JSF provides a declarative approach to build the user interface using JSF and RichFaces tags

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.