<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7110614371420404415</id><updated>2012-01-16T03:22:13.852-07:00</updated><category term='tagHandler'/><category term='EL'/><category term='ViewHandler'/><category term='GWT'/><category term='EditableValueHolder'/><category term='JSP'/><category term='DataModel'/><category term='Seam'/><category term='bug'/><category term='visitTree'/><category term='AJAX'/><category term='JSTL'/><category term='G4Jsf'/><category term='UIData'/><category term='dataTable'/><category term='ADF'/><category term='var'/><category term='dataList'/><category term='forEach'/><category term='facelets'/><category term='iterator'/><category term='ValueExpression'/><category term='VariableMapper'/><category term='choose'/><category term='Ajax4Jsf'/><category term='invokeOnComponent'/><category term='JSF'/><category term='if'/><title type='text'>Discussions and Tutorials on Software Development</title><subtitle type='html'>Discussions on software development, primarily web development including JSF, Python, PHP and JavaScript.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>14</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-9174048535037449677</id><published>2012-01-04T15:54:00.002-07:00</published><updated>2012-01-04T16:57:55.715-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='JSF'/><category scheme='http://www.blogger.com/atom/ns#' term='EL'/><category scheme='http://www.blogger.com/atom/ns#' term='ADF'/><category scheme='http://www.blogger.com/atom/ns#' term='invokeOnComponent'/><category scheme='http://www.blogger.com/atom/ns#' term='visitTree'/><title type='text'>Component scope</title><content type='html'>&lt;p&gt;It is often confusing to users what it means by having a JSF component be "in scope," especially in JSF 2. JSF is processed by a set of phases, each one usually iterates the component tree, acting upon each component in turn. Some components, like the h:dataTable, perform stamping.
&lt;/p&gt;
&lt;p&gt;Note, for more information on stamping, please see my &lt;a href="http://drewdev.blogspot.com/2008/06/understanding-datatable.html"&gt;blog on tables&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;
When a component is being processed, the EL context may be altered. For example, the data table injects "var" and "varStatus" variables into the request scope. This also means that when the table is not being processed, these variables are either not available, or point to another value.&lt;/p&gt;
&lt;p&gt;
This is what I mean by a component being "in scope," that it is currently being processed by the JSF lifecycle or JSF APIs in a manner congruent with the JSF specification for working with components.&lt;/p&gt;
&lt;h2&gt;How a component enters scope&lt;/h2&gt;
&lt;p&gt;A component can enter scope one of three ways:
&lt;ol&gt;
    &lt;li&gt;The JSF lifecycle is being run. This will be the result of calls from methods on the component:
    &lt;ul&gt;
      &lt;li&gt;processDecodes&lt;/li&gt;
      &lt;li&gt;processValidators&lt;/li&gt;
      &lt;li&gt;processUpdates&lt;/li&gt;
      &lt;li&gt;processSaveState&lt;/li&gt;
      &lt;li&gt;processRestoreState&lt;/li&gt;
      &lt;li&gt;broadcast&lt;/li&gt;
    &lt;/ul&gt;&lt;/li&gt;
  &lt;li&gt;During an invokeOnComponent callback&lt;/li&gt;
  &lt;li&gt;During a visitTree callback&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;At any other time, it may not be valid to be interacting with the component. Take for example, using Oracle ADF components, an input text component inside of an iterator:&lt;/p&gt;
&lt;pre&gt;
&amp;lt;af:iterator var="item" value="#{bean.items}"&amp;gt;
  &amp;lt;af:inputText value="#{item.value}" binding="#{bean.inputText}" /&amp;gt;
&amp;lt;/af:iterator&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Now consider this Java code for the bean:&lt;/p&gt;
&lt;pre&gt;
private RichInputText _inputText;

public RichInputText getInputText()
{
  return _inputText;
}

public void setInputText(RichInputText text)
{
  _inputText = text;
}

public Object getValue()
{
  return _inputText == null ? null : _inputText.getValue();
}
&lt;/pre&gt;
&lt;p&gt;Should code call the bean's &lt;code&gt;getValue()&lt;/code&gt; method, what is the outcome? Well that is indeed the problem. Before the JSF view is built, the value will be null as the component has not been bound yet. Between JSF phases, it will also be null because &lt;code&gt;#{item}&lt;/code&gt; will not be present in the EL context.&lt;/p&gt;
&lt;p&gt;As this example shows, the attributes and behavior of the component in question change based on what component is currently being operated on. What makes this even more of an issue, is component frameworks that setup and tear down contexts. For example, Oracle ADF faces has a base component class called a &lt;a href="http://jdevadf.oracle.com/adf-richclient-demo/docs/apidocs/oracle/adf/view/rich/component/fragment/ContextSwitchingComponent.html"&gt;oracle.adf.view.rich.component.fragment.ContextSwitchingComponent&lt;/a&gt;. When a component is processing its JSF lifecycle, or one of its children is being called back via a visitTree or invokeOnComponent call, the setupContext method has been run. If one of these components is accessed through code, and the context has not been set up yet, unreliable results may occur, or even exceptions may be thrown. One use case is of the &lt;a href="http://jdevadf.oracle.com/adf-richclient-demo/docs/tagdoc/af_pageTemplate.html"&gt;ADF page template component&lt;/a&gt;. By using context switching, this component alters the EL context so that facets in the page with the &amp;lt;af:pageTemplate /&amp;gt; tag are executed in the EL context they were defined in, and the components inside the page template definition are executed within the context of the page template definition file.&lt;/p&gt;
&lt;p&gt;Note that JSF 2 has a compound component like the ADF page template, but I am not sure how it handles EL context resultion.&lt;/p&gt;
&lt;p&gt;It is therefore, never a good idea to call methods or evaluate attributes on JSF components unless the caller is sure that the component being accessed is currently in scope. Here is another example:&lt;/p&gt;
&lt;pre&gt;
&amp;lt;af:iterator var="item" value="#{bean.items}"&amp;gt;
  &amp;lt;af:pageTemplate viewId="template.jspx" item="#{item}"&amp;gt;
    &amp;lt;f:facet name="center"&amp;gt;
      &amp;lt;af:outputText id="facetText" value="#{item.itemValue}" /&amp;gt;
    &amp;lt;/f:facet&amp;gt;
  &amp;lt;/f:pageTemplate&amp;gt;
&amp;lt;/af:iterator&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Page definition:&lt;/p&gt;
&lt;pre&gt;...
&amp;lt;af:pageTemplateDef var="attrs"&amp;gt;
  &amp;lt;af:xmlContent&amp;gt;
    &amp;lt;component xmlns="http://xmlns.oracle.com/adf/faces/rich/component"&amp;gt;
      &amp;lt;description&amp;gt;This component lays out an entire page.&amp;lt;/description&amp;gt;
      &amp;lt;facet&amp;gt;
        &amp;lt;description&amp;gt;The center content.&amp;lt;/description&amp;gt;
        &amp;lt;facet-name&amp;gt;center&amp;lt;/facet-name&amp;gt;
      &amp;lt;/facet&amp;gt;
      &amp;lt;attribute&amp;gt;
        &amp;lt;description&amp;gt;the item.&amp;lt;/description&amp;gt;
        &amp;lt;attribute-name&amp;gt;item&amp;lt;/attribute-name&amp;gt;
        &amp;lt;attribute-class&amp;gt;com.mycompany.MyItem&amp;lt;/attribute-class&amp;gt;
      &amp;lt;/attribute&amp;gt;
    &amp;lt;/component&amp;gt;
  &amp;lt;/af:xmlContent&amp;gt;
  &amp;lt;af:iterator var="item" value="#{item.innerItems}"&amp;gt;
    &amp;lt;af:facetRef facetName="center"/&amp;gt;
    &amp;lt;af:outputText id="templateText" value="#{item.itemValue}" /&amp;gt;
  &amp;lt;/af:iterator&amp;gt;
&amp;lt;/af:pageTemplateDef&amp;gt;
&lt;/pre&gt;
&lt;p&gt;This is a very simplified example, but it illustrates the question, what does &lt;code&gt;#{item.itemValue}"&lt;/code&gt; evaluate to? In the facet, this should be the item from the bean's items collection, as shown with the output text with id "facetText". Inside the page template, the value should be the item from the inner items collection of the item passed into the page template, show by the output text with the id "templateText". Depending on when this EL is evaluated, different values will be returned. Therefore, is is crucial, that in order to evaluate the &lt;code&gt;RichOutputText.getValue()&lt;/code&gt; method, that the call is made while that component is "in scope," or "in context."&lt;/p&gt;
&lt;h2&gt;Putting a component into context&lt;/h2&gt;
&lt;p&gt;Components are automatically put into context when they are being validated, updated, broadcasting events, rendering, etc. Sometimes it is necessary to interact with a component outside of its context. For example, perhaps you have backing bean code that wishes to get the input text value. This may be done by knowing a component's client ID, and using the &lt;code&gt;visitTree&lt;/code&gt; method. Here is an example:&lt;/p&gt;
&lt;pre&gt;
public void performAction(ActionEvent evt)
{
  String clientId = "template1:table1:0:firstNameInputText";
  FacesContext facesContext = FacesContext.getCurrentInstance();
  VisitContext visitContext = VisitContext.createVisitContext(facesContext,
    Collections.singleton(clientId), EnumSet.of(SKIP_UNRENDERED));
  GetFirstNameCallback callback = new GetFirstNameCallback();
  facesContext.getViewRoot().visitTree(visitContext, callback);

  String firstName = callback.getFirstName();
  ...
}

private static class GetFirstNameCallback
  implements VisitCallback
{
  private String _firstName;

  public String getFirstName()
  {
    return _firstName;
  }

  public VisitResult visit(
    VisitContext visitContext,
    UIComponent  target)
  {
    RichInputText inputText = (RichInputText)target;
    _firstName = (String)inputText.getValue();
    return VisitResult.COMPLETE;
  }
}
&lt;/pre&gt;
&lt;p&gt;Here the code illustrates how to access the input text value for a component in the first row of a table.&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;Due to the fact that EL is contextual, it is important that any EL based functionality is only accessed in the correct context for that EL. As such, JSF developers should use caution when interacting with components via their Java APIs. Using visit tree should always be considered when trying to access properties from a component in order to ensure that the expected EL context has been setup when the component attempts to access its data. Failing to do so may cause issues with your programs, and even data contamination.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-9174048535037449677?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/9174048535037449677/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=9174048535037449677&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/9174048535037449677'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/9174048535037449677'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2012/01/component-scope.html' title='Component scope'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-5461918165976917791</id><published>2009-02-01T23:50:00.001-07:00</published><updated>2009-02-01T23:51:51.424-07:00</updated><title type='text'>Problems with the Mozilla Component.utils.Sandbox</title><content type='html'>&lt;P&gt;
Writing a Firefox extension can be time consuming for the first time, the documentation is more reference oriented, more oriented to C++ than the JavaScript version, but it is the worst when there are bugs and you waste hours of work. That is what happened to me with the Sandbox APIs of Firefox 3. After talking to members of the FireBug extension on its Google groups forum, I found out that I am not alone with Sandbox frustrations.
&lt;/P&gt;
&lt;H2&gt;The Sandbox&lt;/H2&gt;
&lt;P&gt;
The sandbox, introduced in full in FF3, is a container that allows extension developers to run code in lower security. This is helpful for interacting with browser web pages or for running code from a server. The &lt;A HREF="https://developer.mozilla.org/en/Components.utils.evalInSandbox"&gt;Sandbox API Documentation&lt;/A&gt; is pretty light, and gives no useful examples for real-world applications. The primary use of the sandbox is probably to work with pages, but they show no example on how to do that.
&lt;/P&gt;
&lt;H2&gt;My Problem&lt;/H2&gt;
&lt;P&gt;
When I was working on an extension I write for work, I found that I had some extremely peculiar results. As an illustration, lets say there are two types of JavaScript objects in a page that you want to work with. The first, is a single instance object that looks up other JS objects, and the second, a 'normal' JS object that we want to create. So for my example, lets say we want to lookup an object, pass that object into a constructor and then run a method on that new object:
&lt;/P&gt;
&lt;PRE&gt;
  var obj = TheRegistry.lookupObject('customId1');
  var ref = new ObjectReference(obj);
  ref.save();
&lt;/PRE&gt;
&lt;P&gt;&lt;/P&gt;
&lt;P&gt;
Now, I want to run this code in my extension, so I setup the sandbox and execute the code like this:
&lt;/P&gt;
&lt;PRE&gt;
  var evalInSandbox = function(win, script, vars)
  {
    win = getUnwrapped(win);
    var sandbox = new Components.utils.Sandbox(win);
    sandbox.window = win;
    sandbox.document = sandbox.window.document;
    sandbox.XPathResult = Components.interfaces.nsIDOMXPathResult;
    sandbox.__proto__ = win;
    if (vars)
    {
      for (var prop in vars)
      {
        sandbox[prop] = vars[prop];
      }
    }
    return Components.utils.evalInSandbox(
      "(function() { " + script + "\n })();", sandbox);
  };
  
  var getUnwrapped = function(obj)
  {
    while (obj.wrappedJSObject)
    {
      obj = obj.wrappedJSObject;
    }
    return obj;
  };
  
  var doSomething = function(window)
  {
    evalInSandbox(window,
      "var obj = TheRegistry.lookupObject('customId1');"+
      "var ref = new ObjectReference(obj);"+
      "ref.save();");
  }
&lt;/PRE&gt;
&lt;P&gt;&lt;/P&gt;
&lt;P&gt;
What I was surprised to find out is that &lt;CODE&gt;ref&lt;/CODE&gt; had no 'save' method, but I knew that was not the case. Looking further into it, &lt;CODE&gt;ref == obj&lt;/CODE&gt;. What the heck?! I tried wrapping the code with &lt;CODE&gt;with (window) { ... }&lt;/CODE&gt;, using &lt;CODE&gt;new window.ObjectReference(obj)&lt;/CODE&gt;, but nothing would work. Finally I gave up on the code and used a FireBug technique to inject a script tag into the page's DOM.
&lt;/P&gt;
&lt;H2&gt;Wrap Up&lt;/H2&gt;
&lt;P&gt;
I wrote this article, not to teach, but hopefully to save other people some time so if the google 'mozilla sandbox bugs' or something similar, they may find this. Hopefully Mozilla will fix the sandbox and improve its documentation, but until then, watch out for bugs, and stay away from creating page objects using the 'new' keyword inside of the sandbox, it just doesn't work.
&lt;/P&gt;
&lt;P&gt;
BTW, the google group discussion I mentioned &lt;A HREF="http://groups.google.com/group/firebug/browse_thread/thread/a7dab9e814db4441"&gt;can be found here&lt;/A&gt;.
&lt;/P&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-5461918165976917791?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/5461918165976917791/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=5461918165976917791&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/5461918165976917791'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/5461918165976917791'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2009/02/problems-with-mozilla.html' title='Problems with the Mozilla Component.utils.Sandbox'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-3844302003135605007</id><published>2009-01-27T12:09:00.002-07:00</published><updated>2009-01-27T12:15:02.349-07:00</updated><title type='text'>JSF Component Binding Stinks</title><content type='html'>Whoever came up with JSF component binding should be taken out back. While a nice thought, it really is just a purely awful piece of design and was not thought through at all.

&lt;P&gt;
&lt;B&gt;Too harsh&lt;/B&gt;? Well, it sounds harsh, but when you consider all the flaws and bugs it causes, it isn't. 
&lt;/P&gt;
&lt;H1&gt;1. The problem&lt;/H1&gt;
&lt;P&gt;
I have been telling people on the MyFaces mailing list to always ensure that they use binding with request scope beans, but I have realized that this advice was now bad. My advice should have been to never use binding at all, or to at least only use a setter, but no getter.
&lt;/P&gt;
&lt;P&gt;
The reason behind this, is that there is a fundemental flaw in how binding was designed. Binding is too completely separate pieces of functionality, jammed together in one implementation:
&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Component factory
&lt;LI&gt;Component access from code
&lt;/OL&gt;

&lt;P&gt;
The latter is what people normally use binding for. This is how the framework uses binding in a JSP component tag:
&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Does the tag have the binding attribute set?
  &lt;OL&gt;
  &lt;LI&gt;If so, call the getter method
    &lt;OL&gt;
    &lt;LI&gt;If returns not null, use that value
    &lt;LI&gt;Else, create a new component
      &lt;OL&gt;
      &lt;LI&gt;Call the setter with the new component
      &lt;/OL&gt;
    &lt;/OL&gt;
  &lt;/OL&gt;
&lt;/OL&gt;

&lt;P&gt;
What you now see is that the getter method acts as both a normal JavaBean property getter as well as a factory. The problem is that 90% of the time, the lifetime of this member variable is too long. Almost always, the component in the bean should only be ever stored as long as the view is being processed. Take this example:
&lt;/P&gt;
&lt;P&gt;
Developer has a managed bean with a request scope with a bound component. The page navigates from view1 to view2.
&lt;/P&gt;
&lt;H3&gt;Jspx Code:&lt;/H3&gt;
&lt;PRE&gt;
  &amp;lt;?xml version='1.0' encoding='utf-8'?&amp;gt;
  &amp;lt;jsp:root
    version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:jsp="http://java.sun.com/JSP/Page"&amp;gt;
    &amp;lt;jsp:directive.page contentType="text/html;charset=utf-8"/&amp;gt;
    &amp;lt;f:view&amp;gt;
      &amp;lt;html&amp;gt;
        &amp;lt;body&amp;gt;
          &amp;lt;h:form&amp;gt;
            &amp;lt;h:outputText binding="#{myBean.textComponent}" /&amp;gt;
          &amp;lt;/h:form&amp;gt;
        &amp;lt;/body&amp;gt;
      &amp;lt;/html&amp;gt;
    &amp;lt;/f:view&amp;gt;
  &amp;lt;/jsp:root&amp;gt;
&lt;/PRE&gt;
&lt;P&gt;&lt;/P&gt;
&lt;P&gt;
Now the views would probably be different, but it is not unusual for someone to reuse &lt;CODE&gt;#{myBean.textComponent}&lt;/CODE&gt; in the page. Now what happens is that view1 causes the &lt;CODE&gt;#{myBean.textComponent}&lt;/CODE&gt; to be set since it would return null on the restore view. View 2 is navigated to, but the &lt;CODE&gt;#{myBean.textComponent}&lt;/CODE&gt; returns the component from view 1, so it is not re-created. Now we have an illegal state, a component is shared between two views.
&lt;/P&gt;
&lt;P&gt;
There could have been two ways of fixing this:
&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;There could have been a &lt;CODE&gt;create&lt;/CODE&gt; or &lt;CODE&gt;factory&lt;/CODE&gt; attribute on the JSP tag and &lt;B&gt;only&lt;/B&gt; that attribute could ever create the component and the set method on the &lt;CODE&gt;binding&lt;/CODE&gt; would be used, but &lt;B&gt;never&lt;/B&gt; the getter method.
&lt;LI&gt;The JSP tag component creation should be smart enough to always check that a component is &lt;B&gt;never&lt;/B&gt; shared across views. Therefore, if a binding expression returns a component that already has a parent and by looking up the tree, the view root is not the current view root, a new component should have been created.
&lt;/OL&gt;

&lt;H2&gt;So what is the best work around for this problem?&lt;/H2&gt;
&lt;P&gt;
Well the best solution is to &lt;B&gt;never&lt;/B&gt; use binding under any circumstances, ever, no exceptions. This is the only safe way to write JSF pages. If your bean needs to access a component, use &lt;CODE&gt;findComponent&lt;/CODE&gt; or &lt;CODE&gt;invokeOnComponent&lt;/CODE&gt; to get the component.
&lt;/P&gt;
&lt;P&gt;
The other alternative is to check the view root yourself in you bean when the getter is called. If the view has changed, return null. Example:
&lt;/P&gt;
&lt;PRE&gt;
  package blog;
  
  import java.util.Map;
  
  import javax.faces.component.UIComponent;
  import javax.faces.component.UIViewRoot;
  import javax.faces.context.FacesContext;
  
  public class MyBean
  {
    public void setMyComponent(UIComponent myComponent)
    {
      this.myComponent = myComponent;
    }
  
    public UIComponent getMyComponent()
    {
      checkViewRoot();
      return this.myComponent;
    }
  
    private void checkViewRoot()
    {
      UIViewRoot current = FacesContext.getCurrentInstance().getViewRoot();
      if (this.viewRoot == null || (current != null &amp;amp;&amp;amp; current != this.viewRoot))
      {
        this.viewRoot = current;
        // view is new or has changed, make sure the component is not re-used
        this.myComponent = null;
      }
    }
  
    private UIComponent myComponent;
    private UIViewRoot viewRoot;
  }
&lt;/PRE&gt;
&lt;P&gt;&lt;/P&gt;
&lt;P&gt;
Ugly? Bad performance? Yes! Unfortunately this may be the best solution if you &lt;B&gt;have&lt;/B&gt; to use component binding. From what I have seen from JSF 2.0 I think there may be factory support, so that component binding to be able to gain access to a component in a bean is separated from component creation. I hope so. Until then, I strongly recommend that you forget that the &lt;CODE&gt;binding&lt;/CODE&gt; attribute exists at all.
&lt;/P&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-3844302003135605007?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/3844302003135605007/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=3844302003135605007&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/3844302003135605007'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/3844302003135605007'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2009/01/jsf-component-binding-stinks.html' title='JSF Component Binding Stinks'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-2645444728746670242</id><published>2009-01-19T16:12:00.002-07:00</published><updated>2009-01-19T16:15:31.090-07:00</updated><title type='text'>JSF compared with CGI-like development for small web sites</title><content type='html'>&lt;p&gt;I have been developing small side web sites in PHP, Python and Java. With my primary job working with Java / JSF, I found that it was not my favorite development environment. I thought I would share some of my experiences.
&lt;/p&gt;
&lt;h2&gt; JSF &lt;/h2&gt;

&lt;p&gt;JSF is a great framework, with a lot of promising ideas, but the more I have tried to work with it, the more I find that it may not be the best solution for writing web pages nor small web applications. &lt;/p&gt;
&lt;p&gt;Pros:&lt;/p&gt;&lt;ul&gt;
&lt;li class="u"&gt;Many open source libraries to leverage&lt;/li&gt;
&lt;li class="u"&gt;Large company backing&lt;/li&gt;
&lt;li class="u"&gt;Complex components with 3rd party libraries&lt;/li&gt;
&lt;li class="u"&gt;Code and view are separated&lt;/li&gt;
&lt;li class="u"&gt;Java has good refactoring tools&lt;/li&gt;
&lt;li class="u"&gt;Fail-over, clustering and other robust business features&lt;/li&gt;
&lt;li class="u"&gt;Part of J2EE&lt;/li&gt;
&lt;li class="u"&gt;Built-in validation and conversion&lt;/li&gt;
&lt;li class="u"&gt;3rd party libraries can make AJAX fairly easy&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Cons:&lt;/p&gt;&lt;ul&gt;
&lt;li class="u"&gt;Must be compiled and deployed&lt;/li&gt;
&lt;li class="u"&gt;Too much XML configuration&lt;/li&gt;
&lt;li class="u"&gt;Components are good for 90% of use cases, but severely handicap the other 10%&lt;/li&gt;
&lt;li class="u"&gt;AJAX geared for PPR only, hard to use AJAX for web-service like functionality&lt;/li&gt;
&lt;li class="u"&gt;State saving methodology is abysmal and kills performance and scalability&lt;/li&gt;
&lt;li class="u"&gt;Multi-phased processing on server is confusing to many users&lt;/li&gt;
&lt;li class="u"&gt;Poor CSS support as components and HTML are loosely tied&lt;/li&gt;
&lt;li class="u"&gt;Poor JavaScript library integration&lt;/li&gt;
&lt;li class="u"&gt;Very few web hosting choices
&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt; Comparison with CGI &lt;/h2&gt;

&lt;p&gt;CGI and similar programming usually involves Perl, PHP, Ruby or Python. I have not written Perl in a while as I prefer python and hove not written and Ruby, but I have written full sites in PHP. CGI, or Apache module based languages do not have the framework idea that Java has. Java seeks to give you factories, factories for your factories, paradigms, many standard and rigid APIs, where these other libraries do not. This is a pro. and a con. in my opinion. I love &lt;a href="www.jquery.com"&gt;jQuery&lt;/a&gt; as it makes client side development terrific, I could do a whole set of blogs on it (maybe I will), but it is more easily used from these other languages compared to Java.&lt;/p&gt;
&lt;p&gt;What I find is that even though I love the cool frameworks of Java, the many nice APIs, it is very hard to make a web site with JSF that looks even remotely appealing. From my experience, I can create about a third of a website with jQuery, PHP or Python and PosgreSQL before I have written one page in JSF. This is mostly because of the problem that JSF is too high-level. It does not let me do what I want. In PHP I can loop over a data set and create a table and then easily use jQuery and AJAX to add &amp;amp; remove rows from that table. JSF this is extremely hard, you get validation errors from current rows, the 3rd party render kits never have add &amp;amp; remove rows, their AJAX is almost always built in and you can't customize it.&lt;/p&gt;
&lt;p&gt;What it comes down to is that I do not need help with the GUI and HTML, I just want some help with tedious tasks. JavaScript libraries like jQuery make rapid web development easy as there are a ton of plug-ins written for it, many of which are more customizable than the ones offered for JSF. Since I can design my own site and get low level, I do not have to fight a render kit from JSF, or the phases of JSF, I just write it the way I want. Now for users that may not be the best with HTML and JavaScript, maybe a framework is great.&lt;/p&gt;
&lt;p&gt;Even though this is important, the other thing I love about developing on Apache and not in a JSF server, is that to make a change, I save a file. In Java, I run mvn (Maven 2) to build, then restart Jetty to test. Working with Tomcat, JBoss or another application server is even worse. It just takes too long to work on. I can make a couple of changes and test with PHP when I am still waiting for my Java application server to start up. Not too mention that Java servers tend to be a major RAM hog.
&lt;/p&gt;
&lt;h2&gt; JSF and Component Trees &lt;/h2&gt;

&lt;p&gt;Another thing that keeps bothering me in JSF is the notion of a web application and the component tree. In JSF, the pages are designed to be shown once, but this is not how web applications work. Web applications, should be mostly one web page that changes as I interact with it (like gmail for example). I should not have to wait for full page refreshes all the time. JSF's components can do this, but not the view layer. JSP is horrendous with dynamic includes and Facelets has issues too (mostly tag / tag handler to component ID matching issues). Without dynamic includes, it is very hard to author wizards, or pages that change (not reload).&lt;/p&gt;
&lt;p&gt;I wonder if Google was smart to avoid Java's JSRs and avoid JSF and develop GWT, a web application development framework made for robust clients.
&lt;/p&gt;
&lt;h2&gt; Final thoughts &lt;/h2&gt;

&lt;p&gt;This is truly a blog post, in that I am just sharing some thoughts as they stream from my head to my keyboard. I could say more on the subject, but don't have the time at the moment. Perhaps JSF2 will improve JSF development, but from what I have seen it only goes so far and will have many of the same flaws, although it does have a lot of cool new functionality. &lt;/p&gt;
&lt;p&gt;It will be interesting to see where the space goes in 5 years, but I will be surprised if JSF lasts that long with its current design. I think that high-level frameworks are just too hard to work with. I really see why most web sites are still written using interpreted languages like Perl, PHP and Python. I still love Java and JSF, but for small web sites on the side, I really don't think JSF can compete at all with its light-weight competitors.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-2645444728746670242?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/2645444728746670242/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=2645444728746670242&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/2645444728746670242'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/2645444728746670242'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2009/01/jsf-compared-with-cgi-like-development.html' title='JSF compared with CGI-like development for small web sites'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-6680501148494167165</id><published>2009-01-13T16:13:00.004-07:00</published><updated>2010-10-28T09:19:18.207-06:00</updated><title type='text'>tr:switcher has some lifecycle caveats</title><content type='html'>The &lt;a href="http://myfaces.apache.org/trinidad/index.html"&gt; Apache MyFaces Trinidad&lt;/a&gt; &lt;a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_switcher.html"&gt; &lt;tr:switcher&gt;&lt;/tr:switcher&gt;&lt;/a&gt; has some optimizations in the component that can easily cause application exceptions.&lt;p&gt;&lt;/p&gt;
&lt;p&gt;The switcher only decodes, validates, updates and renders the facet that is currently show. For example:&lt;/p&gt;
&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;tr:switcher&lt;/span&gt; &lt;span class="xnam"&gt;defaultFacet&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.facet}"&lt;/span&gt;&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;"one"&lt;/span&gt; /&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;"two"&lt;/span&gt; /&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;tr:switcher&lt;/span&gt;&amp;gt;&lt;/pre&gt;
&lt;p&gt;If &lt;code&gt;bean.facet&lt;/code&gt; evaluates to "one", then only the facet with that name will be decoded, validated, updated and rendered. This means, that if the bean value is changed, another component will be acted upon. Take this example:&lt;/p&gt;
&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;tr:selectOneChoce&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"soc1"&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.facet}"&lt;/span&gt; &lt;span class="xnam"&gt;autoSubmit&lt;/span&gt;=&lt;span class="xval"&gt;"true"&lt;/span&gt;&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:selectItem&lt;/span&gt; &lt;span class="xnam"&gt;itemLabel&lt;/span&gt;=&lt;span class="xval"&gt;"One"&lt;/span&gt; &lt;span class="xnam"&gt;itemValue&lt;/span&gt;=&lt;span class="xval"&gt;"one"&lt;/span&gt; /&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:selectItem&lt;/span&gt; &lt;span class="xnam"&gt;itemLabel&lt;/span&gt;=&lt;span class="xval"&gt;"Two"&lt;/span&gt; &lt;span class="xnam"&gt;itemValue&lt;/span&gt;=&lt;span class="xval"&gt;"two"&lt;/span&gt; /&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;tr:selectOneChoce&lt;/span&gt;&amp;gt;
&amp;lt;&lt;span class="xtag"&gt;tr:switcher&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"sw1"&lt;/span&gt; &lt;span class="xnam"&gt;defaultFacet&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.facet}"&lt;/span&gt;&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;"one"&lt;/span&gt;&amp;gt;
   &amp;lt;&lt;span class="xtag"&gt;tr:inputText&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"it1"&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.one}"&lt;/span&gt; /&amp;gt;
 &amp;lt;/&lt;span class="xtag"&gt;f:facet&lt;/span&gt;&amp;gt; 
 &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;"two"&lt;/span&gt;&amp;gt;
   &amp;lt;&lt;span class="xtag"&gt;tr:inputText&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"it2"&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.two}"&lt;/span&gt; /&amp;gt;
 &amp;lt;/&lt;span class="xtag"&gt;f:facet&lt;/span&gt;&amp;gt; 
&amp;lt;/&lt;span class="xtag"&gt;tr:switcher&lt;/span&gt;&amp;gt;&lt;/pre&gt;
&lt;p&gt;What will happen is this:&lt;/p&gt;&lt;ol style="list-style-type:decimal;"&gt;
&lt;li class="1"&gt;APPLY_REQUEST_VALUES&lt;ol style="list-style-type:decimal;"&gt;
&lt;li class="11"&gt;soc1 is decoded (submitted value is set)&lt;/li&gt;
&lt;li class="11"&gt;sw1 is decoded&lt;/li&gt;
&lt;li class="11"&gt;it1 is decoded (submitted value is set)&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;
&lt;li class="1"&gt;PROCESS_VALIDATIONS&lt;ol style="list-style-type:decimal;"&gt;
&lt;li class="11"&gt;soc1 is validated (value is converted and set as a local value)&lt;/li&gt;
&lt;li class="11"&gt;sw1 is validated&lt;/li&gt;
&lt;li class="11"&gt;it1 is validated (value is converted and set as a local value)&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;
&lt;li class="1"&gt;UPDATE_MODEL_VALUES&lt;ol style="list-style-type:decimal;"&gt;
&lt;li class="11"&gt;soc1 is updated (backing bean &lt;code&gt;#{bean.facet}&lt;/code&gt; is set to new value)&lt;/li&gt;
&lt;li class="11"&gt;sw1 is updated&lt;/li&gt;
&lt;li class="11"&gt;it2 is update (no submitted or local value)&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;As you can see it1 is decoded and validated, but not updated. it2 is updated but not decoded or validated.&lt;/p&gt;
&lt;p&gt;Now, lets consider the Trinidad tree (&lt;code&gt;UIXTree&lt;/code&gt; component). Inside the decode of the tree, the code ensures that the component has been initialized using its &lt;code&gt;__init()&lt;/code&gt; method. This method ensures that the tree's disclosed and selected row key sets are not null. Since the JSF phases dictate that the decode method will be called before the updateModel method, the init method is not run for the other phases. Now, if the switcher is used as it is above and there is a tree in one of the facets, this means that the tree may not have ever initialized its disclosed row keys.
&lt;/p&gt;
&lt;h3&gt;The 'fix'&lt;/h3&gt;

&lt;p&gt;To ensure that a component's lifecycle is fully run, that means that the switcher's facet cannot be changed between the decode and the end of the update model phase. This basically means that the value should only be changed during the INVOKE_APPLICATION phase. So here is an example of that:&lt;/p&gt;
&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;tr:selectOneChoce&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"soc1"&lt;/span&gt; &lt;span class="xnam"&gt;valueChangeListener&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.switch}"&lt;/span&gt; &lt;span class="xnam"&gt;autoSubmit&lt;/span&gt;=&lt;span class="xval"&gt;"true"&lt;/span&gt;&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:selectItem&lt;/span&gt; &lt;span class="xnam"&gt;itemLabel&lt;/span&gt;=&lt;span class="xval"&gt;"One"&lt;/span&gt; &lt;span class="xnam"&gt;itemValue&lt;/span&gt;=&lt;span class="xval"&gt;"one"&lt;/span&gt; /&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:selectItem&lt;/span&gt; &lt;span class="xnam"&gt;itemLabel&lt;/span&gt;=&lt;span class="xval"&gt;"Two"&lt;/span&gt; &lt;span class="xnam"&gt;itemValue&lt;/span&gt;=&lt;span class="xval"&gt;"two"&lt;/span&gt; /&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;tr:selectOneChoce&lt;/span&gt;&amp;gt;
&amp;lt;&lt;span class="xtag"&gt;tr:switcher&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"sw1"&lt;/span&gt; &lt;span class="xnam"&gt;defaultFacet&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.facet}"&lt;/span&gt; &lt;span class="xnam"&gt;binding&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.switcher}"&lt;/span&gt;&amp;gt;
 &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;"one"&lt;/span&gt;&amp;gt;
   &amp;lt;&lt;span class="xtag"&gt;tr:inputText&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"it1"&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.one}"&lt;/span&gt; /&amp;gt;
 &amp;lt;/&lt;span class="xtag"&gt;f:facet&lt;/span&gt;&amp;gt; 
 &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;"two"&lt;/span&gt;&amp;gt;
   &amp;lt;&lt;span class="xtag"&gt;tr:inputText&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;"it2"&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;"#{bean.two}"&lt;/span&gt; /&amp;gt;
 &amp;lt;/&lt;span class="xtag"&gt;f:facet&lt;/span&gt;&amp;gt; 
&amp;lt;/&lt;span class="xtag"&gt;tr:switcher&lt;/span&gt;&amp;gt;&lt;/pre&gt;
&lt;pre lang="x-java"&gt;public class Bean
{
 private String facet;
 private UIXSwitcher switcher;

 public Bean()
 {
   this.facet = this.selectFacet = 'one';
 }

 public UIXSwitcher getSwitcher() { return this.switcher; }
 public void setSwitcher(UIXSwitcher switcher) { this.switcher = switcher; }

 public String getFacet() { return this.facet; }

 public void switch(ValueChangeEvent event)
 {
   if (event.getPhaseId() != PhaseId.INVOKE_APPLICATION)
   {
     event.setPhaseId(PhaseId.INVOKE_APPLICATION);
     event.queue();
     return;
   }
   this.switcher.setFacetName((String)event.getNewValue());
 }
}&lt;/pre&gt;
&lt;p&gt;Now this is a bit of a hack, but this ensures that the callback to set the switcher only occurs during the correct phase.
&lt;/p&gt;
&lt;h3&gt;Change UIXSwitcher?&lt;/h3&gt;

&lt;p&gt;A very good argument could be made that &lt;code&gt;UIXSwitcher&lt;/code&gt; should not prevent the decoding, validating and updating of all of its children. This would be more acceptible from a JSF perspective. The problem with this is that it would drastically impact performance of users that are expecting this behavior.
&lt;/p&gt;
&lt;h3&gt;Wrap Up&lt;/h3&gt;

&lt;p&gt;The take away, is that any component that affects the lifecycle methods of other components must be used with care. A component should always decode, validate and update in that order, and should never have its lifecycle changed. Hopefully this post will help avoid problems that are not that easy to debug.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-6680501148494167165?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/6680501148494167165/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=6680501148494167165&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/6680501148494167165'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/6680501148494167165'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2009/01/trswitcher-has-some-lifecycle-caveats.html' title='tr:switcher has some lifecycle caveats'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-1234718027801457571</id><published>2009-01-13T10:27:00.001-07:00</published><updated>2009-01-13T10:29:57.872-07:00</updated><title type='text'>New location</title><content type='html'>I am moving my previous blog of &lt;a href="http://andrewfacelets.blogspot.com/"&gt;http://andrewfacelets.blogspot.com&lt;/a&gt; to here. This is to broaden the scope of my blogs to all software development instead of constraining myself to JSF and facelets. Some blogs to be posted here shortly. Thanks for reading.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-1234718027801457571?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/1234718027801457571/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=1234718027801457571&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/1234718027801457571'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/1234718027801457571'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2009/01/new-location.html' title='New location'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-6015007342793060024</id><published>2008-08-10T20:31:00.000-06:00</published><updated>2009-01-13T10:31:46.730-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='VariableMapper'/><category scheme='http://www.blogger.com/atom/ns#' term='JSTL'/><category scheme='http://www.blogger.com/atom/ns#' term='JSF'/><category scheme='http://www.blogger.com/atom/ns#' term='bug'/><category scheme='http://www.blogger.com/atom/ns#' term='ValueExpression'/><title type='text'>c:forEach with JSF could ruin your day</title><content type='html'>&lt;p&gt;Last week, a co-worker of mine at Oracle was attempting to use a &lt;code&gt;forEach&lt;/code&gt; tag to produce components in a loop and developed issues. Having some experience trying to deal with for each I started looking into the problem and found a disturbing problem.&lt;/p&gt;
&lt;p&gt;The JSTL &lt;code&gt;&amp;lt;c:forEach/&amp;gt;&lt;/code&gt; tag was written to make JSP development easier, but was never intended to be used with Java Server Faces. In JSP 2.1 some enhancements were made to improve the usage of non-JSF JSP tags intermingled with JSF by introducing deferred expressions. The idea behind the deferred expressions was to be able to create expressions that would normally have to be evaluated at JSP tag execution and allow them to be executed with JSF components instead. The problem is that the implementation of deferred expressions is flawed for the &lt;code&gt;&amp;lt;c:forEach/&amp;gt;&lt;/code&gt; loop except for basic usage only.
&lt;/p&gt;
&lt;h2&gt;Use Case&lt;/h2&gt;

&lt;p&gt;For the illustration of the problem with the &lt;code&gt;&amp;lt;c:forEach/&amp;gt;&lt;/code&gt; I will simplify the use case. The are two main problems with the tag both of which involve the changing of the list bound to the &lt;code&gt;items&lt;/code&gt; attribute. For the first, consider the following requirements:
&lt;/p&gt;&lt;ul&gt;
&lt;li class="u"&gt;For each loop required, JSF stamped iteration components cannot be used (like JSP tags that include a page)&lt;/li&gt;
&lt;li class="u"&gt;Ajax used to partially render the page&lt;/li&gt;
&lt;li class="u"&gt;Id's of components must be tied to the item in the loop to allow actions
&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Problem 1 - static EL&lt;/h2&gt;

&lt;p&gt;A simple example can be used to show the problem:
&lt;/p&gt;&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;h:form&lt;/span&gt;&amp;gt;
  &amp;lt;&lt;span class="xtag"&gt;c:forEach&lt;/span&gt; &lt;span class="xnam"&gt;var&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;item&amp;quot;&lt;/span&gt; &lt;span class="xnam"&gt;items&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{bean.items}&amp;quot;&lt;/span&gt;&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;h:commandButton&lt;/span&gt;
      &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;button_${var.key}&amp;quot;&lt;/span&gt;
      &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;Remove #{var.key}&amp;quot;&lt;/span&gt;
      &lt;span class="xnam"&gt;actionListener&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{bean.remove}&amp;quot;&lt;/span&gt; /&amp;gt;
  &amp;lt;/&lt;span class="xtag"&gt;c:forEach&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;h:form&lt;/span&gt;&amp;gt;&lt;/pre&gt;
&lt;p&gt;Take for example a list of "A", "B", "C" and "D". The buttons render as:
&lt;/p&gt;&lt;table&gt;&lt;tr&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;ID&lt;/strong&gt; &lt;/td&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;Text&lt;/strong&gt; &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; button_A &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove A &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; button_B &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove B &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; button_C &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove C &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; button_D &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove D &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;p&gt;Now should the user click "Remove A", the managed bean removes the value from the &lt;code&gt;items&lt;/code&gt; list. The result is:&lt;/p&gt;
&lt;table&gt;&lt;tr&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;ID&lt;/strong&gt; &lt;/td&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;Text&lt;/strong&gt; &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; button_B &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove C &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; button_C &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove D &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; button_D &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove  &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;p&gt;Notice the mismatch of ID and text? Notice that the last button's &lt;code&gt;#{var.key}&lt;/code&gt; evaluated to null? &lt;/p&gt;
&lt;p&gt;To understand the problem, it is best to describe a step by step process of how the code works:
&lt;/p&gt;&lt;ol style="list-style-type:decimal;"&gt;
&lt;li class="1"&gt;The for each tag is executed and the first iteration (count 0) is begun&lt;/li&gt;
&lt;li class="1"&gt;The tag creates an &lt;code&gt;IndexedValueExpression&lt;/code&gt;. This sub-class of &lt;code&gt;ValueExpression&lt;/code&gt;.&lt;ul&gt;
&lt;li class="1u"&gt;The expression to get the items is stored (&lt;code&gt;#{bean.items}&lt;/code&gt;)&lt;/li&gt;
&lt;li class="1u"&gt;The index of the for each iteration is stored (&lt;code&gt;0&lt;/code&gt;)&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li class="1"&gt;This &lt;code&gt;IndexedValueExpression&lt;/code&gt; is then added to the &lt;code&gt;VariableMapper&lt;/code&gt; as the &lt;code&gt;var&lt;/code&gt; - item.&lt;/li&gt;
&lt;li class="1"&gt;The body of the tag is executed&lt;/li&gt;
&lt;li class="1"&gt;The command button tag is instructed to create or find a component with ID &lt;code&gt;button_A&lt;/code&gt;. &lt;/li&gt;
&lt;li class="1"&gt;The command button component is created with all its attributes.&lt;ul&gt;
&lt;li class="1u"&gt;When the component is created, the &lt;code&gt;ValueExpression&lt;/code&gt; instances are created&lt;/li&gt;
&lt;li class="1u"&gt;Each &lt;code&gt;ValueExpression&lt;/code&gt; is created with a reference to the &lt;code&gt;FunctionMapper&lt;/code&gt; and &lt;code&gt;VariableMapper&lt;/code&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li class="1"&gt;The for each tag proceeds with its execution and processes indexes 1-3&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;When the action executes and removes A, the following occurs during the render phase. First, the for each tag looks for the button for B and finds it. Then the loop repeats. At the end of processing the tags, the code realizes that &lt;code&gt;button_A&lt;/code&gt; was never referenced, and is therefore removed from its parent, the form.&lt;/p&gt;
&lt;p&gt;The problem is that once the component is created, the &lt;code&gt;ValueExpression&lt;/code&gt; instances are created, and are never re-created. This is because the expressions with their mappers are serialized and restored as part of the component state. This means that &lt;code&gt;button_B&lt;/code&gt; which was found for the first item after item A was removed still has its original &lt;code&gt;ValueExpression&lt;/code&gt; for the &lt;code&gt;value&lt;/code&gt; attribute. This expression has the variable mapper with the indexed value expression for the &lt;code&gt;var&lt;/code&gt; which has index 1. &lt;/p&gt;
&lt;p&gt;This means that if components are used with IDs that tie to the items, it is possible to have the value expressions pointing to the wrong index in the for each loop once changes are made to the items list.
&lt;/p&gt;
&lt;h2&gt;Problem 2 - Component State&lt;/h2&gt;

&lt;p&gt;One workaround to problem one is to use dynamically created IDs. This will violate our above requirement of needing to match the component to the item for advanced PPR (AJAX) replacement, but it is a consideration.&lt;/p&gt;
&lt;p&gt;Lets use the above use case with the IDs removed:
&lt;/p&gt;&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;h:form&lt;/span&gt;&amp;gt;
  &amp;lt;&lt;span class="xtag"&gt;c:forEach&lt;/span&gt; &lt;span class="xnam"&gt;var&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;item&amp;quot;&lt;/span&gt; &lt;span class="xnam"&gt;items&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{bean.items}&amp;quot;&lt;/span&gt;&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;h:commandButton&lt;/span&gt;
      &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;Remove #{var.key}&amp;quot;&lt;/span&gt;
      &lt;span class="xnam"&gt;actionListener&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{bean.remove}&amp;quot;&lt;/span&gt; /&amp;gt;
  &amp;lt;/&lt;span class="xtag"&gt;c:forEach&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;h:form&lt;/span&gt;&amp;gt;&lt;/pre&gt;
&lt;p&gt;This renders as:&lt;/p&gt;
&lt;table&gt;&lt;tr&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;ID&lt;/strong&gt; &lt;/td&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;Text&lt;/strong&gt; &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; j_id_id2 &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove A &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; j_id_id2j_id_1 &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove B &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; j_id_id2j_id_2 &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove C &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; j_id_id2j_id_3 &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove D &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;p&gt;When A is removed, since the item key is not used in the ID, the above problem is not witnessed:&lt;/p&gt;
&lt;table&gt;&lt;tr&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;ID&lt;/strong&gt; &lt;/td&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;Text&lt;/strong&gt; &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; j_id_id2 &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove B &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; j_id_id2j_id_1 &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove C &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; j_id_id2j_id_2 &lt;/td&gt;&lt;td style="text-align:center;"&gt; Remove D &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;p&gt;What you will notice is that item B which used component with ID &lt;code&gt;j_id_id2j_id_1&lt;/code&gt; is now rendered by component with ID &lt;code&gt;j_id_id2&lt;/code&gt;. Unlike above, this component has the correct index stored for it, but its state may break the view. Now command buttons are not a great example of this, but many components have state that is more evident, like tree node expansion. What this will mean to the user is that component state that belongs with item B is now associated with item C. 
&lt;/p&gt;
&lt;h2&gt;How could this be addressed?&lt;/h2&gt;

&lt;p&gt;The fundamental problem is that the implementation of the for each loop tag assumes that the location of the components that are created are independent of the items used to produce them. The &lt;code&gt;ValueExpression&lt;/code&gt; instances are created for components with hard coded indexes and there is no way that I know of to update the index to the correct value later.&lt;/p&gt;
&lt;p&gt;One fix is to allow the for each loop to use keys for the item instead of indexes. The obvious problem with this idea is that it would involve a significant API enhancement to be able to specify a key for an object and the use of a &lt;code&gt;Map&lt;/code&gt; instead of a &lt;code&gt;List&lt;/code&gt; or array to be able to lookup the value for the key. Something like:&lt;/p&gt;
&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;h:form&lt;/span&gt;&amp;gt;
  &amp;lt;&lt;span class="xtag"&gt;c:forEach&lt;/span&gt; &lt;span class="xnam"&gt;var&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;item&amp;quot;&lt;/span&gt; &lt;span class="xnam"&gt;keys&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{items.keys} items=&amp;quot;&lt;/span&gt;#{bean.items}"&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;h:commandButton&lt;/span&gt;
      &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;Remove #{var.key}&amp;quot;&lt;/span&gt;
      &lt;span class="xnam"&gt;actionListener&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{bean.remove}&amp;quot;&lt;/span&gt; /&amp;gt;
  &amp;lt;/&lt;span class="xtag"&gt;c:forEach&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;h:form&lt;/span&gt;&amp;gt;&lt;/pre&gt;
&lt;p&gt;Where keys would be a &lt;code&gt;List&lt;/code&gt; or array of serializable objects for keys in the items which would be represented as a &lt;code&gt;Map&lt;/code&gt;.
&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;As I have always recommended on the Apache MyFaces and Facelets mailing lists the best solution is to never use JSTL tags for JSF development. Unfortunately there are some pieces of functionality which is hard to replicate using components. Perhaps JSF 2.0 will allow things like component controlled sub-page inclusion.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-6015007342793060024?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/6015007342793060024/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=6015007342793060024&amp;isPopup=true' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/6015007342793060024'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/6015007342793060024'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2008/08/cforeach-with-jsf-could-ruin-your-day.html' title='c:forEach with JSF could ruin your day'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-2001937691073333803</id><published>2008-06-07T09:29:00.001-06:00</published><updated>2009-06-22T14:05:10.124-06:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='DataModel'/><category scheme='http://www.blogger.com/atom/ns#' term='dataTable'/><category scheme='http://www.blogger.com/atom/ns#' term='UIData'/><category scheme='http://www.blogger.com/atom/ns#' term='JSF'/><category scheme='http://www.blogger.com/atom/ns#' term='iterator'/><category scheme='http://www.blogger.com/atom/ns#' term='EditableValueHolder'/><category scheme='http://www.blogger.com/atom/ns#' term='var'/><category scheme='http://www.blogger.com/atom/ns#' term='dataList'/><title type='text'>Understanding the dataTable</title><content type='html'>&lt;style type="text/css"&gt;
blockquote {
  background-color: #FFFFCC;
}
&lt;/style&gt;
&lt;p&gt;The &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/h/dataTable.html"&gt; &lt;code&gt;&amp;lt;h:dataTable/&amp;gt;&lt;/code&gt;&lt;/a&gt;, although easy for many to understand to use is often not understood in how it actually works. Since my article on &lt;a href="http://andrewfacelets.blogspot.com/2008/03/build-time-vs-render-time.html"&gt; component tree construction and rendering with respect to JSTL&lt;/a&gt; seemed to be received pretty well, I have decided to cover how the &lt;code&gt;&amp;lt;h:dataTable/&amp;gt;&lt;/code&gt; works.
&lt;/p&gt;
&lt;h2&gt;Table Of Contents&lt;/h2&gt;
&lt;ul&gt;
&lt;li class="u"&gt;&lt;a href="#looping"&gt; Looping components&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#architecture"&gt; General Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#encoding"&gt; Encoding the Children&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#var"&gt; Understanding var&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#phases"&gt; Other Phases&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#clientid"&gt; Understanding Client IDs&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#events"&gt; Event Broadcasting&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#binding"&gt; Binding&lt;/a&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="#conclusion"&gt; Conclusion&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;a name="looping"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Looping components&lt;/h2&gt;
&lt;p&gt;
The dataTable is one of many components that loop, although it is unfortunately the only one provided with core JSF. Other looping components are from 3rd party libraries. Here are some:&lt;/p&gt;&lt;ul&gt;
&lt;li class="u"&gt;&lt;a href="http://myfaces.apache.org/trinidad/index.html"&gt; Apache MyFaces Trinidad&lt;/a&gt;&lt;ul&gt;
&lt;li class="uu"&gt;&lt;a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_iterator.html"&gt; &lt;code&gt;&amp;lt;tr:iterator&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="uu"&gt;&lt;a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_table.html"&gt; &lt;code&gt;&amp;lt;tr:table&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="uu"&gt;&lt;a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_tree.html"&gt; &lt;code&gt;&amp;lt;tr:tree&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="uu"&gt;&lt;a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_treeTable.html"&gt; &lt;code&gt;&amp;lt;tr:treeTable&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="http://myfaces.apache.org/tomahawk/index.html"&gt; Apache MyFaces Tomahawk&lt;/a&gt;&lt;ul&gt;
&lt;li class="uu"&gt;&lt;a href="http://myfaces.apache.org/tomahawk/tlddoc/t/dataList.html"&gt; &lt;code&gt;&amp;lt;t:dataList&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="uu"&gt;&lt;a href="http://myfaces.apache.org/tomahawk/tlddoc/t/dataTable.html"&gt; &lt;code&gt;&amp;lt;t:dataTable&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="uu"&gt;&lt;a href="http://myfaces.apache.org/tomahawk/tlddoc/t/tree2.html"&gt; &lt;code&gt;&amp;lt;t:tree2&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li class="u"&gt;&lt;a href="https://facelets.dev.java.net/nonav/docs/dev/docbook.html"&gt; Facelets&lt;/a&gt;&lt;ul&gt;
&lt;li class="uu"&gt;&lt;a href="https://facelets.dev.java.net/nonav/docs/dev/docbook.html#template-repeat"&gt; &lt;code&gt;&amp;lt;ui:repeat&amp;gt;&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li class="u"&gt;Etc.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Each of these components, although renders quite different HTML all work using a similar design, modeled by the core &lt;code&gt;&amp;lt;h:dataTable/&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a name="architecture"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;General Architecture&lt;/h2&gt;
&lt;p&gt;
The API is simple, but the architecture, not so much. The API involves the construction of a set of components that produce an outer HTML element followed by inner HTML elements. For example, the &lt;code&gt;&amp;lt;h:dataTable/&amp;gt;&lt;/code&gt; creates an outer &lt;code&gt;&amp;lt;TABLE&amp;gt;&lt;/code&gt; with a &lt;code&gt;&amp;lt;TR/&amp;gt;&lt;/code&gt; for each iteration of the loop. Others like &lt;a href="http://myfaces.apache.org/tomahawk/tlddoc/t/dataList.html"&gt; &lt;code&gt;&amp;lt;t:dataList&amp;gt;&lt;/code&gt;&lt;/a&gt;, &lt;a href="https://facelets.dev.java.net/nonav/docs/dev/docbook.html#template-repeat"&gt; &lt;code&gt;&amp;lt;ui:repeat&amp;gt;&lt;/code&gt;&lt;/a&gt; and &lt;a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_iterator.html"&gt; &lt;code&gt;&amp;lt;tr:iterator&amp;gt;&lt;/code&gt;&lt;/a&gt; produce no HTML usually, so they simply allow one to loop over a set of components for many objects in a model.&lt;/p&gt;
&lt;p&gt;Each of these components have &lt;code&gt;value&lt;/code&gt; and &lt;code&gt;var&lt;/code&gt; attributes, although their names may change slightly from component to component. The &lt;code&gt;value&lt;/code&gt; provides some kind of model data to the component. This may be a model class (like a tree model for a tree component), or just object arrays or collections of objects. Each component differs on what values they support, but either way all point to a model of data that contains many objects. When the component is rendered, each object in the model is iterated over. In order for page developers to access the data, an EL variable is injected into scope &lt;strong&gt;temporarily&lt;/strong&gt;. This variable has a name given by the &lt;code&gt;var&lt;/code&gt; attribute. Take for example this code that shows all of the cookies sent to the server in a table in a servlet environment:&lt;/p&gt;
&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;h:dataTable&lt;/span&gt;
  &lt;span class="xnam"&gt;var&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;_cookie&amp;quot;&lt;/span&gt;
  &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{facesContext.externalContext.request.cookies}&amp;quot;&lt;/span&gt;&amp;gt;
  &amp;lt;&lt;span class="xtag"&gt;h:column&lt;/span&gt;&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;header&amp;quot;&lt;/span&gt;&amp;gt;
      &amp;lt;&lt;span class="xtag"&gt;h:outputText&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt; /&amp;gt;
    &amp;lt;/&lt;span class="xtag"&gt;f:facet&lt;/span&gt;&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;h:outputText&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{_cookie.name}&amp;quot;&lt;/span&gt; /&amp;gt;
  &amp;lt;/&lt;span class="xtag"&gt;h:column&lt;/span&gt;&amp;gt;
  &amp;lt;&lt;span class="xtag"&gt;h:column&lt;/span&gt;&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;f:facet&lt;/span&gt; &lt;span class="xnam"&gt;name&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;header&amp;quot;&lt;/span&gt;&amp;gt;
      &amp;lt;&lt;span class="xtag"&gt;h:outputText&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt; /&amp;gt;
    &amp;lt;/&lt;span class="xtag"&gt;f:facet&lt;/span&gt;&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;h:outputText&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{_cookie.value}&amp;quot;&lt;/span&gt; /&amp;gt;
  &amp;lt;/&lt;span class="xtag"&gt;h:column&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;h:dataTable&lt;/span&gt;&amp;gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;value&lt;/code&gt; is an array of &lt;code&gt;Cookie&lt;/code&gt; objects. The &lt;code&gt;var&lt;/code&gt; is "_cookie" (I use an underscore to make sure the name does not intefere with any scoped objects). The table renders the header and footer as a normal JSF component, but then iterates over the data. In this case, it converts the array to a &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/model/DataModel.html"&gt; DataModel&lt;/a&gt;. It then sets the &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/model/DataModel.html#setRowIndex(int)"&gt; &lt;code&gt;rowIndex&lt;/code&gt;&lt;/a&gt; which caused the &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/model/DataModel.html#getRowData()"&gt; &lt;code&gt;rowData&lt;/code&gt;&lt;/a&gt; to return the current cookie (so a row index of 0 returns the first cookie and setting the index to 1 will cause the 2nd cookie to be returned). Basically this is a simple iterator pattern. Some components loop through all, some loop only through a subset (the table can loop through a portion using the &lt;code&gt;rows&lt;/code&gt; and &lt;code&gt;first&lt;/code&gt; attributes). &lt;/p&gt;
&lt;p&gt;The most important thing to note is that even though there may be several cookies, there are only ever 4 &lt;code&gt;outputText&lt;/code&gt; components (1 in each header and one in each column). &lt;/p&gt;
&lt;p&gt;&lt;a name="encoding"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Encoding the Children&lt;/h3&gt;

&lt;p&gt;What happens to produce multiple &lt;code&gt;&amp;lt;TR/&amp;gt;&lt;/code&gt; elements is that the &lt;code&gt;TableRenderer&lt;/code&gt; encodes its children in a loop. Here are the steps of &lt;code&gt;TableRenderer.encodeChildren&lt;/code&gt;:&lt;/p&gt;&lt;ol style="list-style-type:decimal;"&gt;
&lt;li class="1"&gt;get the first row to be rendered from &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getFirst()"&gt; &lt;code&gt;UIData.getFirst()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="1"&gt;get the number of rows to be rendered from &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getRows()"&gt; &lt;code&gt;UIData.getRows()&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li class="1"&gt;write the &lt;code&gt;&amp;lt;TBODY/&amp;gt;&lt;/code&gt; start tag&lt;/li&gt;
&lt;li class="1"&gt;loop until the correct number of rows have been rendered&lt;ol style="list-style-type:decimal;"&gt;
&lt;li class="11"&gt;if &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#isRowAvailable()"&gt; row is not available&lt;/a&gt; then stop&lt;/li&gt;
&lt;li class="11"&gt;render the row, encoding all the children recursively&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;&lt;a name="var"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Understanding "var"&lt;/h3&gt;
&lt;p&gt;
The &lt;code&gt;var&lt;/code&gt; is not controlled by the renderer, but the component, &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html"&gt; &lt;code&gt;UIData&lt;/code&gt;&lt;/a&gt; to be precise. Non-&lt;code&gt;UIData&lt;/code&gt; components that loop perform similar logic if designed after the JSF table. The scope of the &lt;code&gt;var&lt;/code&gt; is limited to when the &lt;code&gt;&amp;lt;t:dataTable/&amp;gt;&lt;/code&gt; is currently iterating. To be exact, it is available when the &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getRowIndex()"&gt; &lt;code&gt;rowIndex&lt;/code&gt;&lt;/a&gt; is not -1. In the &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#setRowIndex(int)"&gt; &lt;code&gt;UIData.setRowIndex(int)&lt;/code&gt;&lt;/a&gt; method, if the index is being set to a value not equal to -1, then the row state is updated for the appropriate index. If the value is -1, the state is cleared.&lt;/p&gt;
&lt;p&gt;The state is comprised of all the children components that implement &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/EditableValueHolder.html"&gt; EditableValueHolder&lt;/a&gt;. So before the row index is changed, &lt;code&gt;UIData&lt;/code&gt; saves the &lt;code&gt;value&lt;/code&gt;, &lt;code&gt;localValueSet&lt;/code&gt;, &lt;code&gt;valid&lt;/code&gt; and &lt;code&gt;submittedValue&lt;/code&gt; properties for each child below the table and restores any state saved for the new index. This means that only &lt;code&gt;EditableValueHolder&lt;/code&gt; components may vary state for different rows. Non-&lt;code&gt;EditableValueHolder&lt;/code&gt; components may only vary their behavior (a.k.a. attributes) per row by using EL expressions that use a value that changes per row, like &lt;code&gt;var&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The code stores the row data for the current row into the request map using the value of &lt;code&gt;var&lt;/code&gt; as the key. When the row index is set to -1, the key and value are removed from the request map. This means that if the &lt;code&gt;var&lt;/code&gt; is the same as another request map variable, it will be overridden and then lost. Therefore, it is very important to use a value for &lt;code&gt;var&lt;/code&gt; that will not conflict with other request map variables. This is why I always prepend my &lt;code&gt;var&lt;/code&gt; values with and underscore.&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;br/&gt;
The &lt;code&gt;var&lt;/code&gt; is only in scope when the &lt;code&gt;UIData&lt;/code&gt;'s row index is not -1. This means that it is not available when the component tree is being built, or usually when accessed from outside the component. If you would like to get access a child component of &lt;code&gt;UIData&lt;/code&gt; with the correct scope, you must set the row index to the desired value, otherwise the data will not be there.&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;a name="phases"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Other Phases&lt;/h2&gt;
&lt;p&gt;
The decode, validate and updating processes of the &lt;code&gt;&amp;lt;h:dataTable/&amp;gt;&lt;/code&gt; work the same way as the rendering. They loop through each row index and invoke the appropriate methods on the children components. Since the code to alter the &lt;code&gt;var&lt;/code&gt; and save and restore the states is in &lt;code&gt;UIData&lt;/code&gt;, the behavior is shared. &lt;/p&gt;
&lt;p&gt;&lt;a name="clientid"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Understanding Client IDs&lt;/h2&gt;
&lt;p&gt;
You may have noticed that the client IDs of looped components are altered in a table. Take this use case:
&lt;/p&gt;&lt;pre lang="x-xml"&gt;&amp;lt;&lt;span class="xtag"&gt;h:dataTable&lt;/span&gt;
  &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;cookies&amp;quot;&lt;/span&gt;
  &lt;span class="xnam"&gt;var&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;_cookie&amp;quot;&lt;/span&gt;
  &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{facesContext.externalContext.request.cookies}&amp;quot;&lt;/span&gt;&amp;gt;
  &amp;lt;&lt;span class="xtag"&gt;h:column&lt;/span&gt;&amp;gt;
    &amp;lt;&lt;span class="xtag"&gt;h:outputText&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;cookieName&amp;quot;&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;#{_cookie.name}&amp;quot;&lt;/span&gt; /&amp;gt;
  &amp;lt;/&lt;span class="xtag"&gt;h:column&lt;/span&gt;&amp;gt;
&amp;lt;/&lt;span class="xtag"&gt;h:dataTable&lt;/span&gt;&amp;gt;
&amp;lt;&lt;span class="xtag"&gt;h:outputText&lt;/span&gt; &lt;span class="xnam"&gt;id&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;after&amp;quot;&lt;/span&gt; &lt;span class="xnam"&gt;value&lt;/span&gt;=&lt;span class="xval"&gt;&amp;quot;After the table&amp;quot;&lt;/span&gt; /&amp;gt;&lt;/pre&gt;
&lt;p&gt;The two &lt;code&gt;&amp;lt;h:outputText/&amp;gt;&lt;/code&gt; components will have different client IDs. The one outside the table will just be "after" (assuming that there are no parent naming containers). The one in the table however will be "cookies:0:cookieName". The number, '0' in this example, will be the row index. This happens because the &lt;code&gt;UIData&lt;/code&gt; component returns a different ID from &lt;a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getClientId(javax.faces.context.FacesContext)"&gt; getClientId&lt;/a&gt; when the row index is not -1. The code from the JSF RI (a.k.a. Mojarra) is:
&lt;/p&gt;&lt;pre lang="x-java"&gt;    @Override
    public String getClientId(FacesContext context)
    {
        String clientId = super.getClientId(context);
        int rowIndex = getRowIndex();
        if (rowIndex == -1)
        {
            return clientId;
        }
        return clientId + NamingContainer.SEPARATOR_CHAR + rowIndex;
    }&lt;/pre&gt;
&lt;p&gt;As you can see, &lt;code&gt;NamingContainer.SEPARATOR_CHAR + rowIndex&lt;/code&gt; is added onto the end of the table's client ID when the row index is not -1. This ID convention stops ID collision in the HTML, but it also is used for event broadcasting.&lt;/p&gt;
&lt;p&gt;&lt;i&gt;Update: 2007-06-22&lt;/i&gt;&lt;br/&gt;
  Just today, I found an &amp;quot;interesting feature&amp;quot; of UIData. After looking into Jira ticket &lt;a href="http://issues.apache.org/jira/browse/TRINIDAD-1514"&gt;TRINIDAD-1514&lt;/a&gt;, I found that UIComponentBase in both the RI as well as MyFaces caches client IDs. This means that a client ID is not re-generated per-stamp. What happens is the UIData has a kluge to surf all of the components recursively of the UIData, setting its ID to the same value. The setId() on UIComponentBase clears the cached client ID, even if the ID is not actually changed by the function. It is an interesting piece of code (a.k.a. ugly hack). I thought it would be good to mention it here.&lt;/p&gt;
&lt;p&gt;&lt;a name="events"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Event Broadcasting&lt;/h2&gt;
&lt;p&gt;
When a child of the table is decoded, it decodes correctly due to the client ID. Take for example an &lt;code&gt;&amp;lt;h:inputText id="myInputText"/&amp;gt;&lt;/code&gt; component that is in a table. Using just two rows as an example here is a map of the client IDs:
&lt;/p&gt;&lt;table&gt;&lt;tr&gt;&lt;td style="text-align:center;"&gt; &lt;strong&gt;Row Index&lt;/strong&gt; &lt;/td&gt;&lt;td style="text-align:left;"&gt;&lt;strong&gt;Client ID&lt;/strong&gt; &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; -1 &lt;/td&gt;&lt;td style="text-align:left;"&gt;myTable:myInputText &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; 0 &lt;/td&gt;&lt;td style="text-align:left;"&gt;myTable:0:myInputText &lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td style="text-align:center;"&gt; 1 &lt;/td&gt;&lt;td style="text-align:left;"&gt;myTable:1:myInputText &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;p&gt;When the renderer for the input text is decoding, it looks for a value submitted by the client using the client ID as the key. Since the client ID changes, the input text correctly decodes the value from the client for the current row index. &lt;/p&gt;
&lt;p&gt;Now this is great for decoding, but a different mechanism must be used for the queuing and the broadcasting of events. The &lt;code&gt;UIData&lt;/code&gt; component wraps all events in a wrapper class that stores the event being queued, the client ID of the &lt;code&gt;UIData&lt;/code&gt; component and the current row index. Here is what each property is used for:
&lt;/p&gt;&lt;dl&gt;&lt;dt&gt;Client ID&lt;/dt&gt;&lt;dd&gt;The client ID is used in case this table is nested in another table. By identifying the event to broadcast using this ID, the framework can ensure events are broadcast to the correct state of a nested looping component.
&lt;/dd&gt;&lt;dt&gt;Event&lt;/dt&gt;&lt;dd&gt;The original event that will be unwrapped during broadcast. The wrapper delegates much of its functionality to the wrapped event (like the phase ID).
&lt;/dd&gt;&lt;dt&gt;Row Index&lt;/dt&gt;&lt;dd&gt;During broadcasting of the event, this stored index is used to correctly re-position the model to the correct row so that the event is fired in the same row state as when it was queued.&lt;/dd&gt;&lt;/dl&gt;
&lt;p&gt;&lt;a name="binding"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Binding&lt;/h2&gt;
&lt;p&gt;
When binding looping components or children of them to managed beans, it is important to realize what the row index is. For example, if you have an &lt;code&gt;&amp;lt;h:commandLink action=#{bean.actionMethod}"/&amp;gt;&lt;/code&gt; component as a child of a column in a table, the action method is run in the scope of the correct row index. This is because the event is wrapped knowing the correct row index. Therefore, your action method may access the current row data. &lt;/p&gt;
&lt;p&gt;Also since the &lt;code&gt;var&lt;/code&gt;'s scope is only valid during iteration, it is not accessible during the construction of the component tree. Therefore and JSP tags or Facelets &lt;code&gt;TagHandler&lt;/code&gt;s may not attempt to retrieve row data using the &lt;code&gt;UIData&lt;/code&gt; APIs.&lt;/p&gt;
&lt;p&gt;&lt;a name="conclusion"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
The data table component and looping components like it re-use a set of components encoded several times, once for each item to be rendered. The value, submitted value, if the component is valid and if the local value is set properties of &lt;code&gt;EditableValueHolder&lt;/code&gt; children components are supported across iteration of the model. Other properties of components are not saved and thus must use EL to vary their behavior based on the current row.&lt;/p&gt;
&lt;p&gt;Client IDs and event wrappers are used to ensure that the event model of JSF is not broken by the iteration of the component.&lt;/p&gt;
&lt;p&gt;Hopefully this helps you understand looping components better and helps you design better pages as a result. Thank you for reading.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-2001937691073333803?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/2001937691073333803/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=2001937691073333803&amp;isPopup=true' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/2001937691073333803'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/2001937691073333803'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2008/06/understanding-datatable.html' title='Understanding the dataTable'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-3522132214763062479</id><published>2008-03-18T09:02:00.000-06:00</published><updated>2009-01-13T10:31:46.786-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='tagHandler'/><category scheme='http://www.blogger.com/atom/ns#' term='JSTL'/><category scheme='http://www.blogger.com/atom/ns#' term='JSP'/><category scheme='http://www.blogger.com/atom/ns#' term='facelets'/><category scheme='http://www.blogger.com/atom/ns#' term='choose'/><category scheme='http://www.blogger.com/atom/ns#' term='JSF'/><category scheme='http://www.blogger.com/atom/ns#' term='ViewHandler'/><category scheme='http://www.blogger.com/atom/ns#' term='forEach'/><category scheme='http://www.blogger.com/atom/ns#' term='if'/><title type='text'>Build time vs. render time</title><content type='html'>&lt;style type="text/css"&gt;
blockquote.note {
  background-color: #FFFFCC;
}
blockquote.note div {
  font-weight: bold;
}
&lt;/style&gt;
&lt;h1&gt;Overview&lt;/h1&gt;
&lt;p&gt;There always seems to be someone posting about how MyFaces or JSF is "broken" and it turns out that they misused JSTL tags. No matter how many times a solution is posted, the issue comes up again. Therefore, I am writing this blog to help those that do not understand how facelets and JSP view handlers work.&lt;/p&gt;
&lt;h1&gt;The Problem&lt;/h1&gt;
&lt;p&gt;JSF works entirely differently than JSP. JSP, when used for JSF, is used to build a JSF component tree, not render a page. JSTL tags alter the contents of what is built, the component tree, not the HTML that is output by the component renderers.&lt;/p&gt;
&lt;h2&gt;A Background of JSP&lt;/h2&gt;
&lt;p&gt;JSP was written so that authoring servlets would be easier. JSP pages are servlets, nothing more. Using a JSP compiler, a JSP file is compiled into a Java Servlet. Before tag libraries were introduced, JSP pages simply were compiled down into &lt;code&gt;System.out.println(...);&lt;/code&gt; statements.&lt;/p&gt;
&lt;p&gt;Tag libraries enhanced JSP by providing an API to tag authors to write Java code that would not have to be embedded in &amp;lt;% ... %&amp;gt; tags. The tags gave developers access to the text content of the tag body so that they could alter it or use it in a custom way. After some time, Sun released the Java standard tag library API, also known as the JSTL.&lt;/p&gt;
&lt;h3&gt;The JSTL&lt;/h3&gt;
&lt;p&gt;The JSTL is a set of JSP tags to perform common JSP functionality (note that they are not related to JSF in any way at all). Many of them perform logic to alter their contents. In the case of &lt;code&gt;c:if&lt;/code&gt; and &lt;code&gt;c:choose&lt;/code&gt;, they choose which tag contents to be included in the response or not.&lt;/p&gt;
&lt;p&gt;I will be mainly talking about the JSTL core tags in this article (catch, choose, forEach, forTokens, if, etc.). It is these that have such a profound, and often confusing to some people, affect on JSF.&lt;/p&gt;
&lt;h2&gt;What JSF Is&lt;/h2&gt;
&lt;p&gt;JSF is a component technology, and architecturally is not related to JSP at all. In fact, using JSP with JSF has drawbacks, included serious performance implications due to the architecture of JSP and how the JSP view handler works.&lt;/p&gt;
&lt;blockquote class="note"&gt;
  &lt;div&gt;Note&lt;/div&gt;
  &lt;p&gt;Sun probably made the default view handler as one that uses JSP, so they would not have to admit that JSP did not meet the needs of users and needed to be replaced.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;Component Technology&lt;/h3&gt;
&lt;p&gt;What I mean by JSF being a component technology, is that HTML is produced by the processing of a component tree by renderers. This design is much more similar to Swing than it is Servlets and JSP. Regardless of the view handler that is used, a tree of components is built.&lt;/p&gt; 
&lt;blockquote class="note"&gt;
  &lt;div&gt;Note&lt;/div&gt;
  &lt;p&gt;A component is simply a Java Object that implements the UIComponent interface, nothing more.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;These components simply store attributes, have some behaviors and are similar in nature to the Swing Tree component. JSF relies on renderers (classes that extend Renderer) to produce content from the component tree. During the restore view, a JSF view should be restored to its previous state, so that it appears to code that there was never a round trip for the code to the client (this is important as I discuss the JSTL tags and especially &lt;code&gt;c:forEach&lt;/code&gt;).&lt;/p&gt;
&lt;blockquote class="note"&gt;
  &lt;div&gt;Note&lt;/div&gt;
  &lt;p&gt;Components do not have to use renderers to produce their content, but it is considered bad design to use the encode methods in a component to render a response.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote class="note"&gt;
  &lt;div&gt;Note&lt;/div&gt;
  &lt;p&gt;JSF is typically used to produce HTML, but can be used to generate any output that doesn't even have to be XML related, although the &lt;code&gt;ResponseWriter&lt;/code&gt;'s API is designed for XML content.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h1&gt;JSF with JSP&lt;/h1&gt;
&lt;p&gt;JSF is implemented using JSP by default (see my note above why this stinks). What this means is that JSP is used to build the JSF component tree. This is important to note because JSP is not used to generate any of the HTML, unlike a typical JSP page. There are two main stages of JSF on JSP:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Building of the component tree using JSP tags&lt;/li&gt;
  &lt;li&gt;Rendering of the component tree using the standard JSF lifecycle&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Building of the component tree using JSP tags&lt;/h2&gt;
&lt;p&gt;As I mentioned earlier, JSF is a component technology. When JSP tags are used, instead of writing text (HTML) onto the servlet response, the tags create components and set attribute values on them. Most of this work is done by &lt;code&gt;UIComponentClassicTagBase&lt;/code&gt;. The class hierarchy is:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;java.lang.Object&lt;/li&gt;
    &lt;ul&gt;
      &lt;li&gt;javax.faces.webapp.UIComponentTagBase&lt;/li&gt;
        &lt;ul&gt;
          &lt;li&gt;javax.faces.webapp.UIComponentClassicTagBase&lt;/li&gt;
            &lt;ul&gt;
              &lt;li&gt;javax.faces.webapp.UIComponentELTag&lt;/li&gt;
              &lt;li&gt;javax.faces.webapp.UIComponentTag&lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The &lt;code&gt;doStartTag&lt;/code&gt; method of &lt;code&gt;UIComponentClassicTagBase&lt;/code&gt; calls &lt;code&gt;findComponent&lt;/code&gt;, which despite its name creates the component (if needed) and calls &lt;code&gt;setProperties&lt;/code&gt;. Therefore, the JSF component is created when the start of the JSP tag is processed. The &lt;code&gt;setProperties&lt;/code&gt; method is responsible for setting the attributes of the component. Typically there is a one-to-one map of JSP tag attribute to JSF component attribute, so the &lt;code&gt;setProperties&lt;/code&gt; simply copies the attributes over, doing any necessary conversion of the string value in the JSP attribute to an object that the component expects for the attribute.&lt;/p&gt;
&lt;h2&gt;How JSTL fits in&lt;/h2&gt;
&lt;p&gt;Most of the "work" of a component takes place during rendering. For example, the &lt;code&gt;h:dataTable&lt;/code&gt; sets up the &lt;code&gt;var&lt;/code&gt; attribute during rendering (and other phases too, but that is not pertinent to this article). This means that EL expressions that rely on variables that only have scope during the rendering phase are not valid during component creation. That is to say, there is no component lifecycle method for when the component is created.&lt;/p&gt;
&lt;p&gt;Since JSTL tags are plain JSP tags and do not involve the JSF lifecycle, they do not have access to the environment that components create, like the &lt;code&gt;var&lt;/code&gt; variable of an &lt;code&gt;h:dataTable&lt;/code&gt;. Take this code for example:&lt;/p&gt;
&lt;blockquote class="largeCode"&gt;&lt;p&gt;
&amp;lt;f:view&amp;gt;
  &amp;lt;h:dataTable var="_row" value="#{bean.rows}&amp;gt;
    &amp;lt;h:column&amp;gt;
      &amp;lt;c:choose&amp;gt;
        &amp;lt;c:when test="#{_row.editable}"&amp;gt;
          &amp;lt;h:inputText value="#{_row.value}" /&amp;gt;
        &amp;lt;/c:when&amp;gt;
        &amp;lt;c:otherwise&amp;gt;
          &amp;lt;h:outputText value="#{_row.value}" /&amp;gt;
        &amp;lt;/c:otherwise&amp;gt;
      &amp;lt;/c:choose&amp;gt;
    &amp;lt;/h:column&amp;gt;
  &amp;lt;/h:dataTable&amp;gt;
&amp;lt;/f:view&amp;gt;
&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Although from the pure XML standpoint this looks valid, it is not. Thinking about what I just said it is a simple problem:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Data table component created from the data table JSP tag&lt;/li&gt;
  &lt;li&gt;Column component created from its JSP tag&lt;/li&gt;
  &lt;li&gt;The when tag in the choose attempts to evaluate &lt;code&gt;#{_row.editable}&lt;/code&gt;
    &lt;ul&gt;
      &lt;li&gt;Since &lt;code&gt;_row&lt;/code&gt; is not bound (yet) in the EL resolver, null is returned&lt;br/&gt;
        (an argument could be made that the EL engine should throw an error or at least give a warning, but that is not how it is designed)&lt;/li&gt;
      &lt;li&gt;Since null is technically false, the &lt;code&gt;outputText&lt;/code&gt; is created instead of the &lt;code&gt;inputText&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;The output text component is created by its tag&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;So the page author was probably expecting that the &lt;code&gt;choose&lt;/code&gt; would be evaluated for every row in the table. But the table has no rows at this point, the component is being created. So, the &lt;code&gt;inputText&lt;/code&gt; component is never created as the &lt;code&gt;when&lt;/code&gt; tag will not process its contents if the test fails.&lt;/p&gt;
&lt;p&gt;The proper solution is to use JSF functionality and not JSP functionality. To the confusion of JSP developers, there are no &lt;code&gt;c:if&lt;/code&gt;, &lt;code&gt;c:choose&lt;/code&gt; or &lt;code&gt;c:forEach&lt;/code&gt; equivalent components (see the &lt;a href="http://myfaces.apache.org/sandbox/limitRendered.html"&gt;Tomahawk Sandbox limitRendered&lt;/a&gt; for &lt;code&gt;c:if&lt;/code&gt; and &lt;code&gt;c:choose&lt;/code&gt; functionality and the &lt;a href="http://myfaces.apache.org/tomahawk/dataList.html"&gt;Tomahawk dataList&lt;/a&gt; or &lt;a href="http://myfaces.apache.org/trinidad/trinidad-1_2/trinidad-api/tagdoc/tr_iterator.html"&gt;Trinidad iterator&lt;/a&gt; components for &lt;code&gt;c:forEach&lt;/code&gt; type of functionality). Without third party components, the rendered attribute can also work, although it requires more work:&lt;/p&gt;
&lt;blockquote class="largeCode"&gt;&lt;p&gt;
&amp;lt;f:view&amp;gt;
  &amp;lt;h:dataTable var="_row" value="#{bean.rows}&amp;gt;
    &amp;lt;h:column&amp;gt;
      &amp;lt;h:inputText value="#{_row.value}" rendered="#{_row.editable}" /&amp;gt;
      &amp;lt;h:outputText value="#{_row.value}" rendered="#{not _row.editable}" /&amp;gt;
    &amp;lt;/h:column&amp;gt;
  &amp;lt;/h:dataTable&amp;gt;
&amp;lt;/f:view&amp;gt;
&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;In this case both the input and the output components are created. The rendered is evaluated by the renderer during the rendering phase while the data table is iterating over each of its rows.&lt;/p&gt;
&lt;h3&gt;When it is okay to use JSP tags with JSF&lt;/h3&gt;
&lt;p&gt;So now that you know the problem, you may ask why is using any non-JSF, JSP tags allowed? This is because they still work, but must be used correctly. Since JSP tags are evaluated while components are being built, they can control which components to create. For example, I may want to include certain components in a page template if the current user is an administrator. Because the components are not created if the user is not an administrator, there will be less components objects created and less components to process for each JSF lifecycle phase, and thus improving performance.&lt;/p&gt;
&lt;p&gt;It is very important to remember that you cannot have components "re-appear" on post back of a JSF form. This is because a JSF component tree should never be altered between having its state saved and when its state is restored. This is very important, so let me say again, &lt;b&gt;a JSF component tree should never be altered between having its state saved and when its state is restored&lt;/b&gt;. The reason is that this would violate the JSF specification/design. Take for example a &lt;code&gt;c:forEach&lt;/code&gt; loop that when evaluated had five items it its list. Assuming that there was one JSF component tag inside the for each tag, that means five components were created. Now JSF saves the state for five components. Then lets say this for each loop data is coming from a database that can change and now there are only four items. When JSF attempts to restore the component tree, there is data for 5 components, but there are only 4 in the component tree. This causes a restore state exception.&lt;/p&gt;
&lt;p&gt;Therefore, always ensure that when a component tree is restored, it is not changed! There is no problem changing a component tree after restoring it or before saving it, only between those times.&lt;/p&gt;
&lt;h1&gt;Hey, what about Facelets?&lt;/h1&gt;
&lt;p&gt;I did mention that I would talk about facelets, didn't I?&lt;/p&gt;
&lt;p&gt;Facelets is similar in its behavior to JSP although it has much more efficient code and is designed quite differently than JSP. Instead of JSP tags, facelets has &lt;code&gt;TagHandler&lt;/code&gt;s. These tag handlers analyze the XML content of a facelet and create components. Just like JSP tags, the tag handlers have no access to the render-time scope of the components. In fact, facelets provides tag handlers to mimic the JSTL functionality. These tag handlers have the same pitfalls as the JSP tags. Therefore, the same considerations and rules apply to tag handlers that apply to JSP tags.&lt;/p&gt;

&lt;h1&gt;Other Blogs&lt;/h1&gt;
&lt;p&gt;Here are some other helpful resources on this topic:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://www.ilikespam.com/blog/c:foreach-vs-ui:repeat-in-facelets"&gt;c:foreach vs ui:repeat in facelets&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-3522132214763062479?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/3522132214763062479/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=3522132214763062479&amp;isPopup=true' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/3522132214763062479'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/3522132214763062479'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2008/03/build-time-vs-render-time.html' title='Build time vs. render time'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-9191956914903447163</id><published>2007-09-17T08:48:00.000-06:00</published><updated>2009-01-13T10:31:46.816-07:00</updated><title type='text'>Trinidad versus Tomahawk component architecture</title><content type='html'>&lt;p&gt;I have been using Tomahawk quite a while and building several custom components with it. Relatively recently, I have incorporated Trinidad in a new project I am working on due to its AJAX support and large number of components.&lt;/p&gt;
&lt;p&gt;Yesterday, I attempted to incorporate maven-faces-plugin into my project from the Trinidad code base. After trying it out, I have decided to back it out of my project, partially due to the amount of work, and mostly due to the architecture of Trinidad components.&lt;/p&gt;
&lt;h2&gt;Why is Tomahawk a better component development platform?&lt;/h2&gt;
&lt;p&gt;Yes, a bold statement, but I wanted to get your attention. Trinidad has a great offering, a lot of components, AJAX support and a good set of APIs, but there may be a large architectural flaw. This flaw is the architecture of Components and renderers around the FacesBean.&lt;/p&gt;
&lt;h3&gt;Comparison:&lt;/h3&gt;
&lt;p&gt;What I found is that Tomahawk follow an OO paradigm, but Trinidad breaks OOD standards. One of the major aspects of effective OOD is encapsulation. This basically means that the functionality an Object provides comes from the component itself. Tomahawk has a special map behind the getAttributes() method of each component. This map delegates the attributes to the property getter and setter methods of the component. Take for example:&lt;/p&gt;
&lt;div class="code"&gt;
// MyComponent comp;
String value = comp.getMyProperty();
value = comp.getAttributes().get("myProperty");
&lt;/div&gt;
&lt;p&gt;These two lines of code are identical in terms of functionality, they both call "getMyProperty()" on MyComponent. This means that component developers know that the getter and setter methods of their component will be called, and they have the control to provide any functionality that is needed besides just storing and retrieving a value (they can manipulate values, check for illegal arguments, etc.). This illustrates a good comprehension of encapsulation, that the functions of MyComponent provide the functionality of MyComponent.&lt;/p&gt;
&lt;p&gt;Trinidad works in a completely different way. Each UIXComponent has a FacesBean instance that is tied to a static Type that dictates what values are stored during state processing of the component. The getter and setter methods of the components retrieve and store values into this FacesBean. The break in encapsulation is that this FacesBean is made public. That means that people can access the FacesBean and get values without a reference to the component. Encapsulation is lost, the component no longer has any control over the functionality for its own properties. To make matters worse, all of the Trinidad JSP Tag classes and the Trinidad renders use this FacesBean directly, taking the component completely out of the picture.&lt;/p&gt;
&lt;h2&gt;Code generation&lt;/h2&gt;
&lt;p&gt;There were other issues that I had with the maven-faces-plugin. The biggest, is that this plugin drastically affects your project layout and architecture. Unlike the Tomahawk code generator which injects code into a component's source, Trinidad actually generates the entire component. This means that the Trinidad components &lt;b&gt;have&lt;/b&gt; to be their own maven project. Furthermore, there is a two step process which requires a third project (i.e. trinidad-build, trinidad-api and trinidad-impl). After refactoring most of my code into this layout, the plugin still didn't work. It wasn't generating the taglib.xml files. Unfortunately the plugin is not documented&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;My conclusion from my research is to not use maven-faces-plugin for my project. For my custom components that extend Trinidad components, I am forced to use the FacesBean architecture or else risk breaking the Trinidad renderers, or at least not being compliant with the design.&lt;/p&gt;
&lt;h3&gt;To the Trinidad team:&lt;/h3&gt;
&lt;p&gt;Adam and the Trinidad team, what do you feel about inversing the FacesBean? What I mean by this, is that currently the get/set component methods store the values into the FacesBean. What about taking the design of the Tomahawk components and having the FacesBean call the get/set methods on the component to get their values and have the get/set methods of the component actually do the work? Since the code is generated, the cascade of the change shouldn't be too bad. Only people that have extended these components without using maven-faces-plugin would be affected.&lt;/p&gt;
&lt;p&gt;Since this would break backwards-compatibility, Trinidad's major version could be bumped.&lt;/p&gt;
&lt;hr /&gt;
&lt;h3&gt;Updates and responses to comments&lt;/h3&gt;
&lt;h4&gt;2007-09-17&lt;/h4&gt;
&lt;p&gt;Simon,&lt;/p&gt;
&lt;p&gt;Yes, I know that the performance will be better and the generated code  smaller, but is that a good reason for breaking standard OOD? With this model, the component's properties are reduced to the security and functionality of public fields.&lt;/p&gt;
&lt;p&gt;I am a very strong believer in usage of OOD for Java objects and the current design forgoes the UIComponent design by having the renderers bypass the component and the component attributes by delegating component properties to the FacesBean.&lt;/p&gt;&lt;p&gt;Is the efficiency of FacesBean worth the cost of bypassing encapsulation and reducing a component's methods to not much more than a Map&lt;String,Object&gt;?&lt;/p&gt;
&lt;p&gt;JDK 1.5 has made reflection much faster, and if the Method references were cached, it would be a much smaller performance hit. Take EJB3 for example, it uses reflection  plus annotations to get and set values for database access. Even though there is a performance hit, the API remains viable for production use.&lt;/p&gt;
&lt;p&gt;Instead of using FacesBean, renderers could use the attribute map instead, this would ensure that renderers remain component agnostic. For example:&lt;/p&gt;
&lt;div class="code"&gt;public void encodeBegin(FacesContext facesContext, UIComponent comp) {
  Map&lt;String, Object&gt; attrs = comp.getAttributes();
  Renderer delegate = getMyRendererDelegate();
  delegate.renderStuff(facesContext, attrs);
}&lt;/div&gt;
&lt;p&gt;Or&lt;/p&gt;
&lt;div class="code"&gt;public void encodeBegin(FacesContext facesContext, UIComponent comp) {
  Map&lt;String, Object&gt; attrs = comp.getAttributes();
  String styleClass = toString(attrs.get("styleClass"));
}
protected String toString(Object obj) {
  return obj == null ? null : obj.toString();
}&lt;/div&gt;

&lt;p&gt;In these crude examples, the renderer doesn't care what the component is, only that the component may (or may not) provide a specific attributes. In the first example, the delegation renderer can access the attributes to get a styleClass for example. The second example shows a class accessing a property via the attributes&lt;/p&gt;
&lt;p&gt;With this paradigm, a renderer developer may choose to access the component directly (cast the component to one it supports) or use the attributes. If it uses the attributes, it choose to be able to support behaviors rather than types. In this way, renderers that are used as delegates could simply rely on the attribute map.&lt;/p&gt;
&lt;p&gt;In terms of performance, the attribute may could cache, in a transient variable, the Method to call for the get and/or set property accessors. The component could choose to use FacesBean, or just store the value in a member variable. I know there is some performance overhead, but this is a side effect of a good encapsulation with the flexibility that you desire from the loose-binding a.k.a. late binding you desire for renderers.&lt;/p&gt;

&lt;h4&gt;2007-09-17&lt;/h4&gt;
Adam,
&lt;p&gt;The reason FacesBean violates OOD is that it delegates the behavior of the UIComponent to the FacesBean. The UIComponent no longer has any control over its own properties and is no longer aware of external accesses to its own data. Also, the way that an object chooses to serialize its data (saveState, restoreState behaviors in JSF), is an internal, not external function.&lt;/p&gt;&lt;p&gt;With the FacesBean being a public object, a piece of code can easily change the value of a property to something illegal, and the component has no opportunity to validate the new value.&lt;/p&gt;&lt;p&gt;Lastly, the component has no control over removing attributes. With proper use of encapsulation, a component could remove an attribute, maintaining the get/set properties as deprecated but store the value elsewhere. With the FacesBean, the component now is permanently bound to the data that it serializes, as people now code against the PropertyKey names instead of the exposed properties. The way that the FacesBean architecture is made, the private fields of UIXComponent have been made public.&lt;/p&gt;

&lt;h4&gt;2007-09-17&lt;/h4&gt;
&lt;p&gt;Simon,&lt;/p&gt;
&lt;p&gt;Good point on the sub-classing FacesBean, perhaps I should give that option more thought. If I have the incentive and time, I may decide to create a new blog entry on customizing the FacesBean to create validation methods, the ability to create access methods (handle set/get) as a proof of concept.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-9191956914903447163?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/9191956914903447163/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=9191956914903447163&amp;isPopup=true' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/9191956914903447163'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/9191956914903447163'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2007/09/trinidad-versus-tomahawk-component.html' title='Trinidad versus Tomahawk component architecture'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-5402231707887896331</id><published>2006-11-18T12:38:00.000-07:00</published><updated>2009-01-13T10:31:46.834-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='GWT'/><category scheme='http://www.blogger.com/atom/ns#' term='AJAX'/><category scheme='http://www.blogger.com/atom/ns#' term='JSF'/><category scheme='http://www.blogger.com/atom/ns#' term='Seam'/><category scheme='http://www.blogger.com/atom/ns#' term='Ajax4Jsf'/><category scheme='http://www.blogger.com/atom/ns#' term='G4Jsf'/><title type='text'>Is JSF made for AJAX or does it just "play along"?</title><content type='html'>&lt;p&gt;Before I begin, this post is meant as a discussion point, not a flame war. I decided to publish this as a blog instead of an email on one of the JSF mailing lists so that I could get comments and feedback from others.&lt;/p&gt;
&lt;p&gt;I have been using JSF for almost two years now, one year as my full time job. It is by far, better than any other server side framework that I have used (C CGI, Perl CGI, PHP, ASP, ASP.NET, JSP and servlets)&lt;/p&gt;

&lt;h2&gt;Background&lt;/h2&gt;
&lt;p&gt;With this in mind, it doesn't mean there aren't issue in the JSF space. One of which is it's compatibility with AJAX. Several competitors are available to use AJAX with JSF:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;AjaxAnywhere&lt;/li&gt;
&lt;li&gt;Ajax4Jsf&lt;/li&gt;
&lt;li&gt;G4Jsf&lt;/li&gt;
&lt;li&gt;Trinidad&lt;/li&gt;
&lt;li&gt;jsf-extensions/Avatar&lt;/li&gt;
&lt;li&gt;ICEFaces&lt;/li&gt;
&lt;li&gt;JBoss-Seam (in the works)&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each of them handle AJAX in their own way unfortunately for the learning user. The one large problem with them, is that they are all on top of JSF. Before you post your comment, here me out. JSF is a "hack" to bring a new technology on top of JSP. It was developed when Sun and Java developers realized that JSP was not succeeding and had fundemental flaws in the design that made ASP.NET, RoR and other languages more appealing. Many went the way of Struts with Java to gain so of that functionality. The problem with struts is that it never provided a good component framework.&lt;/p&gt;

&lt;p&gt;The reason that JSF is a "hack" is that it is built from JSP pages. Although nice to those wishing to convert their projects from plain JSP to JSF with a JSP view handler, the combination is useless for large business applications. "The reason for this?" you ask, well it is the component tree. The single worst design of JSF is the saved component state of the UIViewRoot object. The component tree is made to be built once and then saved on the client or in the user's HttpSession object. This is more than just a serialized set of objects. It has methods for saving state and restoring state that custom components may override. Every time a view is restored, then entire component tree must be recursed and each of these methods are invoked. All the EL expressions (a.k.a. value bindings), component properties, attributes, etc. are all serialized into this component state. The overhead is gigantic.&lt;/p&gt;

&lt;p&gt;To illustrate this point, let me bring up my companies application. It is just that an application, having dockabe frames, complex dialog box, complex layouts, etc. It actually makes Gmail and Google calendar look simplistic. Now I am not trying to pat myself or my company on the back, but let you know of the complexity of each view. There are hundreds if not thousands of components in this component tree. Each time I POST back to the view, the time it takes to restore this component tree is getting slower and slower as we add more functionality.&lt;/p&gt;

&lt;p&gt;Luckily we use Facelets for our view handler not JSP (which I would never recommend as a long term solution). JSP should be though of only as a stepping stone until you convert your legacy application from JSP to JSF. Once you are completely in JSF, use facelets. It is the only way to achieve adequate performance for anything besides a Hello World application.&lt;/p&gt;

&lt;h2&gt;Enter AJAX&lt;/h2&gt;
&lt;p&gt;We are using AjaxAnywhere right now. It is very stable in 1.1.0.6 and does the job nicely. If I were to do it all again, I would probably use Ajax4Jsf due to its tight integration with JSF and the fact that it is the closest in design to Avatar (the future of AJAX in JSF from Sun).&lt;/p&gt;

&lt;h3&gt;The problem&lt;/h3&gt;
&lt;p&gt;For each AJAX request, the "JSF integrated" technologies must post back to JSF. They then execute the standard JSF lifecycle. This includes the restoring of the component tree. Yes, this is the single worst part of JSF for AJAX. If I simply want to update 2 components on the page, I have to restore the entire tree, counting possibly into the 1000s of components. Sound like a bottleneck? It is!&lt;/p&gt;

&lt;p&gt;I can witness this problem when I use JBoss-Seam remoting. Remoting is independent of JSF and therefore does not restore the component tree or the view. I have extended it in my use to integrate with the FacesContext so that I can access &amp; update my backing beans as well. The performance? -- instant. That is right, it doesn't even appear to go back to the server it is so fast. The difference between this and the page POST of AjaxAnywhere back to JSF is huge. Unfortunately, using Java methods on the server to generate HTML feels like the days of pre-JSP servlet development, so while it is good for sending &amp;amp; getting data, it is not a good fit for generating HTML (unless you love JavaScript and you build the entire page via document.createElement() calls -- see my discussion on GWT below).&lt;/p&gt;

&lt;p&gt;What can be done? Well many of these technologies "hack and slash" their way into the JSF APIs to try to speed performance. They skip phases such as validation, updating of the model, etc. for components that do not need to change, but the component tree is still always restored. The one solution is that the component tree must go! That is right, in order for JSF to have adequate performance the JSF specifications must be completely changed to mostly remove the component tree. If I want to update 2 components using AJAX, only those two components should be reloaded from the view, no more. This is problematic as the API is not built for this.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://weblogs.java.net/blog/jhook/"&gt;Jacob Hookom&lt;/a&gt; has had some really good insights on this issue:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://weblogs.java.net/blog/jhook/archive/2006/01/experiment_goin_1.html"&gt;Experiment: Going Stateless with JSF&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://weblogs.java.net/blog/jhook/archive/2006/02/new_feature_for.html"&gt;New Feature for JSF 1.2&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;

&lt;h2&gt;Is the grass greener?&lt;/h2&gt;
&lt;p&gt;I was looking at GWT the other day as it came up when I was looking for some good JavaScript libraries for layouts. In doing so, I started to read more and more, liking it quite a bit. Wondering if this is better for business applications than JSF, I found &lt;a href="http://ajaxian.com/archives/gwt-jsf-g4jsf"&gt;G4Jsf&lt;/a&gt;, an attempt at integration of JSF and GWT. The problem is that I could not find any documentation and the demo is extremely simplistic (no forms, no validation or updating of the JSF model, no JSF navigation, and almost no Views, just GWT code). I will be quite anxious to see where this project goes.&lt;/p&gt;

&lt;p&gt;From what I understand in my initial look, GWT is interesting in that it stores the component state in the DOM of the browser using HTML + JavaScript. This means that when calls are made to the server, there is no component tree to update, no view to restore. The client is almost a thick client (and almost getting the performance of one). It's "magic" is to convert Java code into JavaScript, hiding the complexity of writing JavaScript DOM manipulation code by hand.&lt;/p&gt;

&lt;p&gt;On the other hand GWT doesn't look like a good tool to create web pages though. There is no HTML for developers, only Java code. WYSIWYG is next to impossible from what I see for complex applications. The ease of using the JSF view and the Facelets templates, just doesn't seem to be there.&lt;/p&gt;

&lt;h2&gt;What Now?&lt;/h2&gt;
&lt;p&gt;As I mentioned, the whole point of this blog is simply to start a discussion. I would love to hear what the JSF experts have to say and if they know if future releases beyond 1.2 will start to address these issues (I even wonder if 1.2 will ever take off as ppl. aren't even fully embracing 1.1 yet).&lt;/p&gt;

&lt;p&gt;Is there something I missed with these JSF AJAX libraries to get around the component tree performance issue?&lt;/p&gt;

&lt;p&gt;Please keep the comments to Java based technologies as they apply to JSF, this is not meant to be language war.&lt;/p&gt;

&lt;h2&gt;Update: 2007-04-22&lt;/h2&gt;
&lt;p&gt;Since I created this post, I have had the opportunity to convert my company's software over from AjaxAnywhere to Ajax4Jsf and I wanted to report my findings so far. After some initial issues on converting some very large (and nested) templates over and converting some complex in-house components to A4J, we are now running on A4J with only some minor patching.&lt;/p&gt;

&lt;p&gt;Even with a very large component tree, I am seeing ~300-600ms per AJAX request (calculated using FireBug in Firefox). I am using ajaxSingle="true", limitToList="true" and a4j:region tags where possible to enhance performance (it make a significant performance impact). With time permitting, I think I can get performance better by working on our in-house JavaScript code that runs per-AJAX request that is part of the issue. &lt;/p&gt;

&lt;p&gt;So even though JSF needs some large improvements to the specification to make AJAX fit better, the performance is definitely dependent on the AJAX tools used. Hopefully we see JSF more stream-lined and less JSP dependent (or hopefully completely separate from JSP) in JSF 2.0 with some improvements to component creation and state saving (letting the view handler take more of the burden on and less on the component develeper).&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-5402231707887896331?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/5402231707887896331/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=5402231707887896331&amp;isPopup=true' title='10 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/5402231707887896331'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/5402231707887896331'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2006/11/is-jsf-made-for-ajax-or-does-it-just.html' title='Is JSF made for AJAX or does it just &amp;quot;play along&amp;quot;?'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>10</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-1287454797327422530</id><published>2006-06-27T10:54:00.000-06:00</published><updated>2009-01-13T10:31:46.859-07:00</updated><title type='text'>MyFaces Tree2 - Creating a lazy loading tree</title><content type='html'>&lt;blockquote&gt;Note: this code is hosted at http://sourceforge.net/projects/jsf-comp under the AjaxAnywhere download. As a result, this blog post's content may be out of date compared to that source.&lt;/blockquote&gt;

&lt;p&gt;Although the &lt;a href="http://wiki.apache.org/myfaces/Tree2"&gt;MyFaces Tree2 WIKI&lt;/a&gt; discusses lazy loading children tree nodes, it does not cover the use case of if you don't know if there are children or not. Recently, I had a use case where I was loading children using a WebService that would return me contents of a node per-call. Obviously for performance reasons, I wanted to keep the number of calls to a minumum.&lt;/p&gt;

&lt;p&gt;My approach:&lt;br/&gt;
Use AJAX via &lt;a href="http://ajaxanywhere.sf.net"&gt;AjaxAnywhere&lt;/a&gt; and server-side toggling with Tree2 to lazy load the tree nodes. When asked for the children of a node that isn't loaded, I would load the nodes then and there.&lt;p&gt;

&lt;p&gt;My use case was wrapped around a content management solution, so it was file/directory based nodes.&lt;/p&gt;

What was needed:
&lt;ul&gt;&lt;li&gt;Custom tree node for "directory nodes"&lt;/li&gt;
&lt;li&gt;Custom tree nodes for "file nodes" that could be selected&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;Note: this blog will not discuss AJAX and enabling the tree in server side mode, that would be another discussion entirely&lt;/blockquote&gt;
&lt;p&gt;
Step 1: create a "lazy loading" tree node that we can extend:&lt;/p&gt;
&lt;blockquote class="largeCode"&gt;public class BaseTreeNode
  implements TreeNode
{
  private BaseTreeNode parent;
  private String identifier;
  private String name;
  private String type;
  protected List&amp;lt;BaseTreeNode&amp;gt; children;
  protected TreeModel model;
  
  public BaseTreeNode() {}
  
  public BaseTreeNode(TreeModel model,
    BaseTreeNode parent, String type, String identifier, 
    String name, boolean leaf)
  {
    this.model = model;
    this.type = type;
    this.parent = parent;
    this.identifier = identifier;
    this.name = name;
    
    if (leaf)
      children = Collections.emptyList();
  }
  
  /**
   * @return Returns the parent.
   */
  public BaseTreeNode getParent()
  {
    return this.parent;
  }

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#isLeaf()
   */
  public boolean isLeaf()
  {
    return getChildCount() == 0;
  }

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#setLeaf(boolean)
   */
  public void setLeaf(boolean leaf) {}

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#getChildren()
   */
  public List&amp;lt;BaseTreeNode&amp;gt; getChildren()
  {
    if (children == null)
      children = loadChildren();
    
    return children;
  }

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#getType()
   */
  public String getType()
  {
    return type;
  }

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#setType(java.lang.String)
   */
  public void setType(String type)
  {
    this.type = type;
  }

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#getDescription()
   */
  public String getDescription()
  {
    return name;
  }

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#setDescription(java.lang.String)
   */
  public void setDescription(String description) {}

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#setIdentifier(java.lang.String)
   */
  public void setIdentifier(String identifier) {}

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#getIdentifier()
   */
  public String getIdentifier()
  {
    return identifier;
  }
  
  public int getIndex()
  {
    return (parent == null) ? 0 : parent.getChildren().indexOf(this); 
  }
  
  /**
   * @return Returns the name.
   */
  public String getName()
  {
    return this.name;
  }  
  
  public String getFullPath()
  {
    StringBuilder sb = new StringBuilder(name);
    
    for (BaseTreeNode node = getParent(); node != null;
      node = node.getParent())
      sb.insert(0, '/').insert(0, node.getName());
    
    return sb.toString();
  }
  
  public String getNodePath()
  {
    StringBuilder sb = new StringBuilder(Integer.toString(getIndex()));
    
    for (BaseTreeNode node = getParent(); node != null;
      node = node.getParent())
      sb.insert(0, TreeModel.SEPARATOR).insert(0, node.getIndex());
    
    return sb.toString();
  }
  
  public boolean isExpanded()
  {
    if (model == null) return true;
    
    return model.getTreeState()
      .isNodeExpanded(getNodePath());
  }

  /**
   * @see org.apache.myfaces.custom.tree2.TreeNode#getChildCount()
   */
  public int getChildCount()
  {
    if (children == null &amp;&amp; !isExpanded())
      return 1;
    
    if (children == null)
      children = loadChildren();
    
    if (children == null)
      return 0;
    
    return children.size();
  }
  
  /**
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return name;
  }
  
  protected List&amp;lt;BaseTreeNode&amp;gt; loadChildren() 
  { 
    return null; 
  }
}&lt;/blockquote&gt;

&lt;p&gt;This base class takes most of the tedious work away from having to create the lazy loading functionality. In the constructor, a "lazy" parameter is provided for nodes that the user knows will not have children (like a file node in this example). This node also includes code for working with the Tree2 default TreeModel and TreeState by implementing a "getNodePath" function that works with node indexes instead of just node IDs.&lt;/p&gt;

&lt;p&gt;Step 2: create the directory node (inner class):&lt;/p&gt;
&lt;blockquote class="largeCode"&gt;public class FolderNode
  extends BaseTreeNode
{
  FolderNode(TreeModel model, BaseTreeNode parent, String name)
  {
    super(model, parent, "folder", name, name, false);
  }
    
  @Override
  protected List&amp;lt;BaseTreeNode&amp;gt; loadChildren()
  {
    return &amp;lt;Your business code class here&amp;gt;.loadChildren(this);
  }
}&lt;/blockquote&gt;
&lt;p&gt;The implementation of the folder is simple. I have not shown my code, but I have this node in my code as an inner class that I have this "loadChildren" method that calls my Web service. In that method, I simply create new nodes an add them to the parent node.&lt;/p&gt;

&lt;p&gt;The key here is how the tree2 works and how the renderer works (this is source code specific, so if Tree2 was changed drastically enough, this may break). The tree2 renderer looks only at the getChildCount method, not the getChildren method when rendering. Meaning that if getChildCount should return 0, getChildren will never be called unless the node is expanded. In my base node, you will see that I am returning 1 child as the child count if the children have not been loaded and the node is not expanded. This will cause tree2 to render a plus sign icon next to my node (indicating that there are children).&lt;/p&gt;

&lt;p&gt;If the node is expanded, and the children are not loaded, my base node then calls the load children method. This will force the accurate count of nodes to be returned for this node. If I were to only put my loading code in the getChildren, the tree would not render correctly, as getChildCount is always called first in the renderer.&lt;/p&gt;

&lt;p&gt;What ends up being the result is that when the plus sign is clicked, the node is exanded in the tree model's tree state. Then the tree is rendered (having the getChildCount method called). I load the children, and return the correct count to the renderer which then proceeds in calling getChildren and building the HTML.&lt;/p&gt;

&lt;p&gt;This will work if there are actually no children (the plus sign simply dissappears), or if there are many children (not the "1" that was originally reported as the number of children).&lt;/p&gt;

&lt;p&gt;FYI, here is the "file" node code:&lt;/p&gt;
&lt;blockquote class="largeCode"&gt;public class FileNode
  extends BaseTreeNode
{
  FileNode(TreeModel model, BaseTreeNode parent, String name)
  {
    super(model, parent, "file", name, name, true);
  }
}&lt;/blockquote&gt;
The XHTML is as follows:
&lt;blockquote class="largeCode"&gt;&amp;lt;aa:zoneJSF id="treeZone"&amp;gt;
  &amp;lt;my:ajaxTree
    value="#{contentMgmtBean.treeModel}"
    ajaxZone="treeZone"
    var="_node"
    clientSideToggle="false"
    varNodeToggler="t"
    showRootNode="false"&amp;gt;
    &amp;lt;f:facet name="folder"&amp;gt;
      &amp;lt;t:panelGroup&amp;gt;
        &amp;lt;t:graphicImage
          styleClass="treeNodeIcon"
          url="#{_node.expanded ?
            '/images/contentMgmt/openfolder.gif' :
            '/images/contentMgmt/closedfolder.gif'}" /&amp;gt;
        &amp;lt;t:outputText
          styleClass="folderNodeText"
          value="#{_node.name}" /&amp;gt;
      &amp;lt;/t:panelGroup&amp;gt;
    &amp;lt;/f:facet&amp;gt;
    &amp;lt;f:facet name="file"&amp;gt;
      &amp;lt;my:ajaxCommandLink
        ajaxZone="treeZone,myResultZone"
        actionListener="#{contentMgmtBean.nodeSelected}"
        styleClass="fileNodeLink#{
          contentMgmtBean.currentFileName eq _node.name ?
          ' selectedNode' : ''}"&amp;gt;
        &amp;lt;t:updateActionListener
          property="#{contentMgmtBean.currentFileName}"
          value="#{_node.name}" /&amp;gt;
        &amp;lt;t:graphicImage
          styleClass="treeNodeIcon"
          url="/images/contentMgmt/file.gif" /&amp;gt;
        &amp;lt;t:outputText
          styleClass="fileNodeText"
          value="#{_node.name}" /&amp;gt;
      &amp;lt;/ost:ajaxCommandLink&amp;gt;
    &amp;lt;/f:facet&amp;gt;
  &amp;lt;/my:ajaxTree&amp;gt;
&amp;lt;/aa:zoneJSF&amp;gt;
&lt;/blockquote&gt;

&lt;p&gt;Example of using the node as an inner class:&lt;/p&gt;
&lt;blockquote class="largeCode"&gt;public class BeanClass
{
 private TreeModel treeModel;

 public List&amp;lt;BaseTreeNode&amp;gt; loadChildren(FolderNode parent)
 {
   List&amp;lt;BaseTreeNode&amp;gt; children = new ArrayList&lt;BaseTreeNode&gt;();
   List&amp;lt;String&amp;gt; folders = ; // load from web service
   for (String folder : folders)
     children.add(new FolderNode(treeModel, parent, folder));
   List&amp;lt;String&amp;gt; files = ; // load from web service
   for (String file : files)
     children.add(new FileNode(treeModel, parent, file));
   return children;
 }

 public class FolderNode
   extends BaseTreeNode
 {
   ...
   protected List&amp;lt;BaseTreeNode&amp;gt; loadChildren()
   {
     return loadChildren(this);
   }
 }
}&lt;/blockquote&gt;

&lt;p&gt;&lt;span style="font-weight: bolder; font-size: large"&gt;Update&lt;/span&gt;
This code has been moved to a jsf-comp component. Go to
&lt;a href="http://sf.net/projects/jsf-comp"&gt;http://sf.net/projects/jsf-comp&lt;/a&gt;
to download. An example war file is included in the release&lt;/p&gt;

© Copyright 2006 - Andrew Robinson.&lt;br/&gt;
Please feel free to use in your applications under the LGPL license (&lt;a href="http://www.gnu.org/licenses/lgpl.html"&gt;http://www.gnu.org/licenses/lgpl.html&lt;/a&gt;).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-1287454797327422530?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/1287454797327422530/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=1287454797327422530&amp;isPopup=true' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/1287454797327422530'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/1287454797327422530'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2006/06/myfaces-tree2-creating-lazy-loading.html' title='MyFaces Tree2 - Creating a lazy loading tree'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-1514276611002701307</id><published>2006-06-18T14:25:00.000-06:00</published><updated>2009-01-13T10:31:46.879-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='JSF'/><title type='text'>Running actions despite validation errors</title><content type='html'>&lt;p&gt;Recently, I was developing a page that had 3 data tables. Each table had an 'add' button and each row in the table had 'delete' buttons. The problem was that I ended up fighting the JSF specification trying to accomplish this simple task.&lt;/p&gt;
&lt;p&gt;The functionality that I wanted for my users was to add or remove rows from these tables regardless of if the data on the rest of the page was valid.&lt;/p&gt;
Table of contents:
&lt;ol&gt;
&lt;li&gt;&lt;a href="#first"&gt;Immediate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#second"&gt;Action validation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#third"&gt;Tomahawk sandbox subForm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#forth"&gt;Optional validator framework&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="#fifth"&gt;New component (solution)&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a name="first"&gt;First&lt;/a&gt; I tried the immediate attribute on my command links. Although this technically worked, I lost all my data in the data table input components. Due to the way the UIData component works, the submitted values will not be correctly processed unless the validation phase is run.&lt;/p&gt;

&lt;p&gt;&lt;a name="second"&gt;After that&lt;/a&gt;, I looked into using only action validation (no validators or required flags). Once again I didn't get the functionality that I desired. It was not possible, while maintaining a clean Object-Oriented design to be able to correctly assign component IDs to the validation messages for the components in the tables (I would have to hard-code the indexes into the messages as well as the view IDs - not an elegant solution).&lt;/p&gt;

&lt;p&gt;The &lt;a name="third"&gt;third&lt;/a&gt; attempt led me to the subForm Tomahawk component from MyFaces. First problem was that the all the components in the form had to be within a subForm. Then I had to create a dummy sub-form that I would submit:&lt;/p&gt;
&lt;blockquote class="code"&gt;&amp;lt;f:form&amp;gt;
  &amp;lt;s:subForm id="mainForm"&amp;gt;
    &amp;lt;-- Other input componenets here --&amp;gt;
    &amp;lt;t:commandLink action="#{userBean.addEmail}"
      actionFor="dummyForm" /&amp;gt;
    &amp;lt;/subForm&amp;gt;
  &amp;lt;s:subForm id="dummyForm" /&amp;gt;
&lt;/blockquote&gt;
&lt;p&gt;Once again this worked only half-way. My action was run, but like with the immediate attribute, the values were lost in the data tables.&lt;/p&gt;

&lt;p&gt;&lt;a name"forth"&gt;Forth&lt;/a&gt; attempt was a look at the Optional validator framework from http://jsf-comp.sf.net. This would have worked but it didn't have the functionality I needed. For one, only validators with IDs were supported (no attributes could be passed, so I would not be able to use validators like validate length which takes a maximum and minimum value. It is also not able to handle required validators on child components of data tables.&lt;/p&gt;

&lt;p&gt;Seeing as how my problem again and again was the phase in which my action was executed, I need a different solution in terms of JSF phase. If immediate was set to true, the action would run but the validation phase would be skipped. The validation phase is needed for the submitted values of data tables though. Having the action fire during model update meant that the validation phase had to be skipped or there had to be a way to skip validation errors.&lt;/p&gt;

&lt;p&gt;My &lt;a name="fifth"&gt;fifth&lt;/a&gt; and final attempt ended up being my solution. It is perhaps not too pretty, but it got the job done. I needed to get the action event to fire during the process validators phase (in between when immediate fires it and non-immediate). I couldn't just extend command link though because UICommand always sets the phase ID of action events during queueEvent. I could have made a special action event that just disabled the setPhaseId funciton (by doing nothing in the method body), but I thought that more of a hack than my final solution.&lt;/p&gt;

&lt;p&gt;My solution was to create a component thats sole purpose in life would be to alter the phase ID of an action event. It would need no renderer either. In the queueEvent I would simple set any ActionEvent's phase IDs to process validation. Then, placing this new component as the parent of an action component (or components), I would make sure my action would run during validation.&lt;/p&gt;

&lt;p&gt;Using facelets, I needed no tag, so I just wrote the component and gave it an active attribute in case I ever want to disable the behavior using EL:&lt;/p&gt;
&lt;blockquote class="largeCode"&gt;import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.event.ActionEvent;
import javax.faces.event.FacesEvent;
import javax.faces.event.PhaseId;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Andrew Robinson (andrew)
 */
public class UIValidationActionPhase
  extends UIComponentBase
{
  private static final Log log = LogFactory.getLog(
    UIValidationActionPhase.class);

  public static final String COMPONENT_FAMILY = "-- set family here --";
  public static final String COMPONENT_TYPE = "-- set component type here --";

  private Boolean active;

  /**
   * @return Returns the active.
   */
  public boolean isActive()
  {
    if (active != null) return this.active;
    ValueBinding vb = getValueBinding("active");
    return (vb == null) || (Boolean)vb.getValue(getFacesContext());
  }

  /**
   * @param active The active to set.
   */
  public void setActive(boolean active)
  {
    this.active = active;
  }

  /**
   * @see javax.faces.component.UIComponent#getFamily()
   */
  @Override
  public String getFamily()
  {
    return COMPONENT_FAMILY;
  }

  /**
   * @see javax.faces.component.UIComponentBase#getRendererType()
   */
  @Override
  public String getRendererType()
  {
    return null;
  }

  /**
   * @see javax.faces.component.UIComponentBase#queueEvent(javax.faces.event.FacesEvent)
   */
  @Override
  public void queueEvent(FacesEvent event)
  {
    if (event instanceof ActionEvent &amp;&amp; isActive())
    {
      log.debug("Changing Phase ID of action event " + event);
      event.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
    }

    super.queueEvent(event);
  }

  /**
   * @see javax.faces.component.UIComponentBase#saveState(javax.faces.context.FacesContext)
   */
  @Override
  public Object saveState(FacesContext context)
  {
    return new Object[] {
      super.saveState(context),
      active,
    };
  }

  /**
   * @see javax.faces.component.UIComponentBase#restoreState(javax.faces.context.FacesContext, java.lang.Object)
   */
  @Override
  public void restoreState(FacesContext context, Object state)
  {
    Object[] array = (Object[])state;
    int index = -1;
    super.restoreState(context, array[++index]);
    active = (Boolean)array[++index];
  }
}
&lt;/blockquote&gt;
The usage in my XHTML file was simple:
&lt;blockquote class="code"&gt;&amp;lt;f:form&amp;gt;
  &amp;lt;my:validationAction&amp;gt;
    &amp;lt;t:commandLink action="#{userBean.addEmail}" /&amp;gt;
  &amp;lt;/my:validationAction&amp;gt;
&amp;lt/f:form&amp;gt;
&lt;/blockquote&gt;
&lt;p&gt;Now the user is able to see validation errors and get feedback on bad input data and my action was still able to run with the validation errors. Luckily my actions (add and delete) did not depend on the model being updated. This solution will not work for those that would need data from the user to be applied to the model.&lt;/p&gt;

© Copyright 2006 - Andrew Robinson.&lt;br/&gt;
Please feel free to use in your applications under the LGPL license &lt;br/&gt;(http://www.gnu.org/licenses/lgpl.html).&lt;br/&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th colspan="2"&gt;
        Updates/Change log
      &lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;th&gt;
        Date
      &lt;/th&gt;
      &lt;th&gt;
        Description
      &lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;2007.03.07&lt;/td&gt;
      &lt;td&gt;Fixed some of the code in the component that was a result of pasting the code into the blog incorrectly.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2007.04.22&lt;/td&gt;
      &lt;td&gt;Reformatting of HTML in blog.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-1514276611002701307?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/1514276611002701307/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=1514276611002701307&amp;isPopup=true' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/1514276611002701307'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/1514276611002701307'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2006/06/running-actions-despite-validation.html' title='Running actions despite validation errors'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7110614371420404415.post-7140233044181978216</id><published>2006-06-14T12:34:00.000-06:00</published><updated>2009-01-13T10:31:46.697-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='facelets'/><category scheme='http://www.blogger.com/atom/ns#' term='JSF'/><title type='text'>Creating composite controls with JSF and facelets</title><content type='html'>&lt;p&gt;JSF, although a powerful framework does not have many tools to assist in the development of composite controls. Whether building a control that has a few controls in it or a control comprised of 100s of children, there is no easy solution. The JSF specification was more written to build components that render themselves entirely.&lt;/p&gt;
&lt;p&gt;With that said &lt;a href="https://facelets.dev.java.net"&gt;Facelets&lt;/a&gt; is a great add on to JSF and has some great templating features. Using a user tag (a.k.a. source tag),  a composite control can be easily created. The trouble is that it  is not possible out-of-the-box to pass method bindings to children components.&lt;/p&gt;
For example:&lt;br/&gt;
Snippet from taglib.xml:
&lt;blockquote class="code"&gt;&amp;lt;tag&amp;gt;
&amp;lt;tag-name&amp;gt;test&amp;lt;/tag-name&amp;gt;
&amp;lt;source&amp;gt;tags/testTag.xhtml&amp;lt;/source&amp;gt;
&amp;lt;/tag&amp;gt;&lt;/blockquote&gt;
Usage in an XHTML file:
&lt;blockquote  class="code"&gt;&amp;lt;my:test actionListener="#{myBean.doSomething}" /&amp;gt;&lt;/blockquote&gt;

User Tag file:
&lt;blockquote class="code"&gt;&amp;lt;ui:composition&amp;gt;
  &amp;lt;h:commandButton value="Click Me" actionListener="#{actionListener}" /&amp;gt;
&amp;lt;/ui:composition&amp;gt;&lt;/blockquote&gt;

&lt;p&gt;The problem with the above code is that the user tag handler of facelets always creates ValueExpression objects for each attribute in the source tag. This is fine for properties, but in the above case, a MethodExpression is what &amp;quot;ought&amp;quot; to be created.&lt;/p&gt;

&lt;p&gt;I wanted to solve this problem, but in such a way to avoid people having to create new tag handlers or component handlers. I wanted a re-usable complete solution. After dragging myself through the mire of source code, I found what I needed in the facelets API to extend it. My solution is two part:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create a tag handler with component support&lt;/li&gt;
&lt;li&gt;Create a new value expression that returns method expressions&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Creating a value expression that is a method expression&lt;/h3&gt;
&lt;p&gt;The second step above is easiest to discuss first. The idea is to have a value expression that returns a method expression as its value. This will allow &amp;quot;#{myBean.doSomething}&amp;quot; to be interpreted as a method instead of a property called "getDoSomething"&lt;/p&gt;
&lt;p&gt;The code below may need some work to be more "correct", but it does work:&lt;/p&gt;
&lt;blockquote class="code"&gt;import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.el.ValueExpression;

public class MethodValueExpression
  extends ValueExpression
  implements Externalizable
{
  private ValueExpression orig;
  private MethodExpression methodExpression;
  
  public MethodValueExpression() {}
  
  MethodValueExpression(ValueExpression orig, MethodExpression methodExpression)
  {
    this.orig = orig;
    this.methodExpression = methodExpression;
  }
  
  @Override
  public Class getExpectedType()
  {
    return orig.getExpectedType();
  }

  @Override
  public Class getType(ELContext ctx)
  {
    return MethodExpression.class;
  }

  @Override
  public Object getValue(ELContext ctx)
  {
    return methodExpression;
  }

  @Override
  public boolean isReadOnly(ELContext ctx)
  {
    return orig.isReadOnly(ctx);
  }

  @Override
  public void setValue(ELContext ctx, Object val) {}

  @Override
  public boolean equals(Object val)
  {
    return orig.equals(val);
  }

  @Override
  public String getExpressionString()
  {
    return orig.getExpressionString();
  }

  @Override
  public int hashCode()
  {
    return orig.hashCode();
  }

  @Override
  public boolean isLiteralText()
  {
    return orig.isLiteralText();
  }
  
  /**
   * @see java.io.Externalizable#readExternal(java.io.ObjectInput)
   */
  public void readExternal(ObjectInput in)
    throws IOException, ClassNotFoundException
  {
    orig = (ValueExpression)in.readObject();
    methodExpression = (MethodExpression)in.readObject();
  }
  
  /**
   * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
   */
  public void writeExternal(ObjectOutput out)
    throws IOException
  {
    out.writeObject(orig);
    out.writeObject(methodExpression);
  }
}
&lt;/blockquote&gt;
&lt;p&gt;Now that we have a value expression that will wrap a method expression, we need to be able to "replace" them into the JSF environment. When facelets is applying components to the tree, it has an EL context that can be used to interpret data. If we know the method signatures of the methods to bind to, we will be able to create MethodExpression objects.&lt;/p&gt;
&lt;p&gt;Lets start with the constructor. We want to create an attribute that will be our configuration. Unfortunately, an attribute can only be given once, so I will create a custom format that we will be able to use. Starting code:&lt;/p&gt;
&lt;blockquote class="code"&gt;public class CompositeControlHandler
  extends TagHandler
{
  private final TagAttribute methodBindings;
  
  private ComponentHandler componentHandler;
  
  /**
   * @param config
   */
  public CompositeControlHandler(TagConfig config)
  {
    super(config);
    methodBindings = getAttribute("methodBindings");
  }
  // TODO...
}
&lt;/blockquote&gt;
&lt;p&gt;We now have a skeleton in which we can declare a "methodBindings" attribute of our custom tag. This will be used to define which variables in the scope of our user tag should be considered methods instead of variables. I have choosen the following format:&lt;/p&gt;
&lt;blockquote class="code"&gt;attribute-name=java-return-type first-java-parameter-type second-java-parameter-type;
second-attribute-name=java-return-type first-java-parameter-type second-java-parameter-type;
&lt;/blockquote&gt;
Example from above:
&lt;blockquote class="code"&gt;actionListener=void javax.faces.event.ActionEvent;
&lt;/blockquote&gt;
&lt;p&gt;So now that we have a way to specify what attributes are now methods, we need to do the work.&lt;/p&gt;Steps:
&lt;ol&gt;
&lt;li&gt;Parse the attribute&lt;/li&gt;
&lt;li&gt;For each attribute, see if the value is "bound" in the current variable mapper&lt;/li&gt;
&lt;li&gt;If bound, create a new method expression from the configuration information&lt;/li&gt;
&lt;li&gt;Hide the initial variable with the method expression&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The resultant code is as follows:&lt;/p&gt;
&lt;blockquote class="code"&gt;public class CompositeControlHandler
  extends TagHandler
{
  private final static Pattern METHOD_PATTERN = Pattern.compile(
    "(\\w+)\\s*=\\s*(.+?)\\s*;\\s*");
  
  private final TagAttribute methodBindings;
  
  /**
   * @param config
   */
  public CompositeControlHandler(TagConfig config)
  {
    super(config);
    methodBindings = getAttribute("methodBindings");
  }

  /**
   * @see com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext, javax.faces.component.UIComponent)
   */
  public void apply(FaceletContext ctx, UIComponent parent)
    throws IOException, FacesException, FaceletException, ELException
  {
    VariableMapper origVarMap = ctx.getVariableMapper();
    
    try
    {
      VariableMapperWrapper variableMap = new VariableMapperWrapper(origVarMap);
      ctx.setVariableMapper(variableMap);
      
      if (methodBindings != null)
      {
        String value = (String)methodBindings.getValue(ctx);
        Matcher match = METHOD_PATTERN.matcher(value);
        
        while (match.find())
        {
          String var = match.group(1);
          ValueExpression currentExpression = origVarMap.resolveVariable(var);
          if (currentExpression != null)
          {
            try
            {
              FunctionMethodData methodData = new FunctionMethodData(
                var, match.group(2).split("\\s+"));
              
              MethodExpression mexpr = buildMethodExpression(ctx, 
                currentExpression.getExpressionString(), methodData);
              variableMap.setVariable(var, new MethodValueExpression(
                currentExpression, mexpr));
            }
            catch (Exception ex)
            {
              throw new FacesException(ex);
            }
          }
        }
      }
      
      // TODO: will do this next
    }
    finally
    {
      ctx.setVariableMapper(origVarMap);
    }
  }
  
  private MethodExpression buildMethodExpression(FaceletContext ctx, String expression,
    FunctionMethodData methodData)
    throws NoSuchMethodException, ClassNotFoundException
  {
    return ctx.getExpressionFactory().createMethodExpression(ctx, expression, 
      methodData.getReturnType(), methodData.getArguments());
  }
  
  private class FunctionMethodData
  {
    private String variable;
    private Class returnType;
    private Class[] arguments;
    
    FunctionMethodData(String variable, String[] types)
      throws ClassNotFoundException
    {
      this.variable = variable;
      if ("null".equals(types[0]) || "void".equals(types[0]))
        returnType = null;
      else
        returnType = ReflectionUtil.forName(types[0]);
      arguments = new Class[types.length - 1];
      for (int i = 0; i &lt; arguments.length; i++)
        arguments[i] = ReflectionUtil.forName(types[i + 1]);
    }
    
    public Class[] getArguments()
    {
      return this.arguments;
    }
    
    public void setArguments(Class[] arguments)
    {
      this.arguments = arguments;
    }
    
    public Class getReturnType()
    {
      return this.returnType;
    }
    
    public void setReturnType(Class returnType)
    {
      this.returnType = returnType;
    }
    
    public String getVariable()
    {
      return this.variable;
    }
    
    public void setVariable(String variable)
    {
      this.variable = variable;
    }
  }
}&lt;/blockquote&gt;
&lt;p&gt;Now, that we have has this much fun, why not instead of just having a tag handler, but a component handler as well. The next steps will allow this user tag to be used without any XML configuration. The goal is to allow the user to specify the component type and renderer type for a component that should be created for our user tag (If none is given, the ComponentRef from facelets will be used).&lt;/p&gt;

&lt;p&gt;The code isn't much different, so I will show it in its entirety here:&lt;/p&gt;
&lt;blockquote class="code"&gt;public class CompositeControlHandler
  extends TagHandler
{
  private final static Pattern METHOD_PATTERN = Pattern.compile(
    "(\\w+)\\s*=\\s*(.+?)\\s*;\\s*");
  
  private final TagAttribute rendererType;
  private final TagAttribute componentType;
  private final TagAttribute methodBindings;
  
  private ComponentHandler componentHandler;
  
  /**
   * @param config
   */
  public CompositeControlHandler(TagConfig config)
  {
    super(config);
    rendererType = getAttribute("rendererType");
    componentType = getAttribute("componentType");
    methodBindings = getAttribute("methodBindings");
    
    componentHandler = new ComponentRefHandler(new ComponentConfig() {
      /**
       * @see com.sun.facelets.tag.TagConfig#getNextHandler()
       */
      public FaceletHandler getNextHandler()
      {
        return CompositeControlHandler.this.nextHandler;
      }
      
      public Tag getTag()
      {
        return CompositeControlHandler.this.tag;
      }

      public String getTagId()
      {
        return CompositeControlHandler.this.tagId;
      }
      
      /**
       * @see com.sun.facelets.tag.jsf.ComponentConfig#getComponentType()
       */
      public String getComponentType()
      {
        return (componentType == null) ?
          ComponentRef.COMPONENT_TYPE :
          componentType.getValue();
      }
      
      /**
       * @see com.sun.facelets.tag.jsf.ComponentConfig#getRendererType()
       */
      public String getRendererType()
      {
        return (rendererType == null) ?
          null : rendererType.getValue();
      }
    });
  }

  /**
   * @see com.sun.facelets.FaceletHandler#apply(com.sun.facelets.FaceletContext, javax.faces.component.UIComponent)
   */
  public void apply(FaceletContext ctx, UIComponent parent)
    throws IOException, FacesException, FaceletException, ELException
  {
    VariableMapper origVarMap = ctx.getVariableMapper();
    
    try
    {
      VariableMapperWrapper variableMap = new VariableMapperWrapper(origVarMap);
      ctx.setVariableMapper(variableMap);
      
      if (methodBindings != null)
      {
        String value = (String)methodBindings.getValue(ctx);
        Matcher match = METHOD_PATTERN.matcher(value);
        
        while (match.find())
        {
          String var = match.group(1);
          ValueExpression currentExpression = origVarMap.resolveVariable(var);
          if (currentExpression != null)
          {
            try
            {
              FunctionMethodData methodData = new FunctionMethodData(
                var, match.group(2).split("\\s+"));
              
              MethodExpression mexpr = buildMethodExpression(ctx, 
                currentExpression.getExpressionString(), methodData);
              variableMap.setVariable(var, new MethodValueExpression(
                currentExpression, mexpr));
            }
            catch (Exception ex)
            {
              throw new FacesException(ex);
            }
          }
        }
      }
      
      componentHandler.apply(ctx, parent);
    }
    finally
    {
      ctx.setVariableMapper(origVarMap);
    }
  }
  
  private MethodExpression buildMethodExpression(FaceletContext ctx, String expression,
    FunctionMethodData methodData)
    throws NoSuchMethodException, ClassNotFoundException
  {
    return ctx.getExpressionFactory().createMethodExpression(ctx, expression, 
      methodData.getReturnType(), methodData.getArguments());
  }
  
  private class FunctionMethodData
  {
    private String variable;
    private Class returnType;
    private Class[] arguments;
    
    FunctionMethodData(String variable, String[] types)
      throws ClassNotFoundException
    {
      this.variable = variable;
      if ("null".equals(types[0]) || "void".equals(types[0]))
        returnType = null;
      else
        returnType = ReflectionUtil.forName(types[0]);
      arguments = new Class[types.length - 1];
      for (int i = 0; i &lt; arguments.length; i++)
        arguments[i] = ReflectionUtil.forName(types[i + 1]);
    }
    
    public Class[] getArguments()
    {
      return this.arguments;
    }
    
    public void setArguments(Class[] arguments)
    {
      this.arguments = arguments;
    }
    
    public Class getReturnType()
    {
      return this.returnType;
    }
    
    public void setReturnType(Class returnType)
    {
      this.returnType = returnType;
    }
    
    public String getVariable()
    {
      return this.variable;
    }
    
    public void setVariable(String variable)
    {
      this.variable = variable;
    }
  }
}&lt;/blockquote&gt;
&lt;p&gt;Now we need to register this in a taglib.xml so that we can use it:&lt;/p&gt;
&lt;blockquote class="code"&gt;&amp;lt;tag&amp;gt;
  &amp;lt;tag-name&amp;gt;compositeControl&amp;lt;/tag-name&amp;gt;
  &amp;lt;handler-class&amp;gt;mypackage.CompositeControlHandler&amp;lt;/handler-class&amp;gt;
&amp;lt;/tag&amp;gt;&lt;/blockquote&gt;
Now that it is registered, lets use it. The XHTML file that uses the tag hasn't changed:
&lt;blockquote class="code"&gt;&amp;lt;my:test actionListener="#{myBean.doSomething}" /&amp;gt;&lt;/blockquote&gt;
The user tag does look different, but not that much:
&lt;blockquote class="code"&gt;&amp;lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&amp;gt;
&amp;lt;html 
  xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:my="http://mynamespace"&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;ui:composition&amp;gt;
      &amp;lt;my:compositeControl
        id="#{id}"
        methodBindings="action=java.lang.String;
          actionListener=void javax.faces.event.ActionEvent;"&amp;gt;
        &amp;lt;ui:debug /&amp;gt;
        &amp;lt;h:commandButton value="Click me"
          actionListener="#{actionListener}"
          action="#{action}" /&amp;gt;
      &amp;lt;/my:compositeControl&amp;gt;
    &amp;lt;/ui:composition&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/blockquote&gt;
That should be enough to get you going.
&amp;copy; Copyright 2006 - Andrew Robinson.
Please feel free to use in your applications under the LGPL license (&lt;a href="http://www.gnu.org/licenses/lgpl.html" target="_blank"&gt;http://www.gnu.org/licenses/lgpl.html&lt;/a&gt;).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7110614371420404415-7140233044181978216?l=drewdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://drewdev.blogspot.com/feeds/7140233044181978216/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=7110614371420404415&amp;postID=7140233044181978216&amp;isPopup=true' title='20 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/7140233044181978216'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7110614371420404415/posts/default/7140233044181978216'/><link rel='alternate' type='text/html' href='http://drewdev.blogspot.com/2006/06/creating-composite-controls-with-jsf.html' title='Creating composite controls with JSF and facelets'/><author><name>Andrew Robinson</name><uri>https://profiles.google.com/105604510721881151324</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh6.googleusercontent.com/-vfsaEv1RrSE/AAAAAAAAAAI/AAAAAAAAAas/kgrkULCksQo/s512-c/photo.jpg'/></author><thr:total>20</thr:total></entry></feed>
