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 panel.setStyle("width:400px"); // 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 panel.getChildren().add(outputText);
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