Tuesday, March 17, 2009

Create your JSF componenst with out JSP or Facelets Tags

It is personal reference. Some love XML Syntax, some try to save them from the XML Jungle. JSF is a framework that allows you to create components dynamically. The JSF Tags are only option.

If you prefer to create your compnents without JSP or Facelets, and you don't want to envent the weel again, you can define your JSF Panel Grid in your JSP or Facelet as follow:





Define the bean in Spring config file as follow:





This bean holds a instance of the JSF HtmlPanelGrid which renders the JSF Panel Grid for you. The JSF components should be added to the Panel Grid with it's public method getChildren().add(Object o);. Here is the example:


package org.mypackage;

import javax.faces.application.Application;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.context.FacesContext;


public class MyBean {

private HtmlPanelGrid panelGrid;

public MyBean(){

}
public void init(){

Application application = FacesContext.getCurrentInstance().getApplication();
setPanelGrid((HtmlPanelGrid) application.createComponent(HtmlPanelGrid.COMPONENT_TYPE));

HtmlOutputText text = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);

text.setValue("Hallo JSF with out Tags.");

getPanelGrid().getChildren().add(text);

}
public void setPanelGrid(HtmlPanelGrid panelGrid) {
this.panelGrid = panelGrid;
}
public HtmlPanelGrid getPanelGrid() {
return panelGrid;
}

}

  1. In line 16 is the public method which will be ivoked by Spring after instantiation of the Bean.
  2. Line 18 gets an instance of the current application.
  3. On line 19 we create an instance of HtmlOutputText with the help of the method createComponent which takes String as argument. Every JSF Component defines public static field COMPONENT_TYPE which returns the type of the component to be created.
  4. On line 21 a instance of HtmlOutputText is created in the same way as the HtmlOutputText.
  5. In line 23 we set the value of the output text.
  6. In line 25 we set the output text component as child of the Panel Grid.
On the end of the day, when JSF try's to render the Panel Grid with the ID dynamic in the JSP or Facelets, the Property panelGrid of the backing bean will be called and our instance would be copied and rendered.

In this way, we can create whole views or parts of it, as if we program in pure Java.

No comments:

Post a Comment