tag:blogger.com,1999:blog-297171042024-03-07T01:06:13.912-07:00Working with JSF and FaceletsCode snippets, discussion and general comments on MyFaces, JSF and the Facelets projectAnonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.comBlogger10125tag:blogger.com,1999:blog-29717104.post-69354825504268173042009-01-13T17:14:00.002-07:002009-01-13T17:14:46.746-07:00New post on new siteFYI, a new post on the Trinidad switcher has been published at the new location:
<a href="http://drewdev.blogspot.com/2009/01/trswitcher-has-some-lifecycle-caveats.html">http://drewdev.blogspot.com/2009/01/trswitcher-has-some-lifecycle-caveats.html</a>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.comtag:blogger.com,1999:blog-29717104.post-7168194615907034412009-01-13T10:32:00.000-07:002009-01-13T10:33:34.076-07:00RelocatedThis blog has moved to <a href="http://drewdev.blogspot.com/">http://drewdev.blogspot.com/</a>. This is to broaden the scope of my blogs to all software development instead of constraining myself to JSF and facelets. All my previous posts have been imported into the new location.
Thanks for reading.Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com0tag:blogger.com,1999:blog-29717104.post-36031027093117602342008-08-10T20:31:00.002-06:002009-05-01T13:53:30.938-06:00c:forEach with JSF could ruin your dayMy blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2008/08/cforeach-with-jsf-could-ruin-your-day.html">You can find this article here</a>
<div style="display: none">
<p>Last week, a co-worker of mine at Oracle was attempting to use a <code>forEach</code> 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.</p>
<p>The JSTL <code><c:forEach/></code> 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 <code><c:forEach/></code> loop except for basic usage only.
</p>
<h2>Use Case</h2>
<p>For the illustration of the problem with the <code><c:forEach/></code> 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 <code>items</code> attribute. For the first, consider the following requirements:
</p><ul>
<li class="u">For each loop required, JSF stamped iteration components cannot be used (like JSP tags that include a page)</li>
<li class="u">Ajax used to partially render the page</li>
<li class="u">Id's of components must be tied to the item in the loop to allow actions
</li></ul>
<h2>Problem 1 - static EL</h2>
<p>A simple example can be used to show the problem:
</p><pre lang="x-xml"><<span class="xtag">h:form</span>>
<<span class="xtag">c:forEach</span> <span class="xnam">var</span>=<span class="xval">"item"</span> <span class="xnam">items</span>=<span class="xval">"#{bean.items}"</span>>
<<span class="xtag">h:commandButton</span>
<span class="xnam">id</span>=<span class="xval">"button_${var.key}"</span>
<span class="xnam">value</span>=<span class="xval">"Remove #{var.key}"</span>
<span class="xnam">actionListener</span>=<span class="xval">"#{bean.remove}"</span> />
</<span class="xtag">c:forEach</span>>
</<span class="xtag">h:form</span>></pre>
<p>Take for example a list of "A", "B", "C" and "D". The buttons render as:
</p><table><tr><td style="text-align:center;"> <strong>ID</strong> </td><td style="text-align:center;"> <strong>Text</strong> </td></tr>
<tr><td style="text-align:center;"> button_A </td><td style="text-align:center;"> Remove A </td></tr>
<tr><td style="text-align:center;"> button_B </td><td style="text-align:center;"> Remove B </td></tr>
<tr><td style="text-align:center;"> button_C </td><td style="text-align:center;"> Remove C </td></tr>
<tr><td style="text-align:center;"> button_D </td><td style="text-align:center;"> Remove D </td></tr></table>
<p>Now should the user click "Remove A", the managed bean removes the value from the <code>items</code> list. The result is:</p>
<table><tr><td style="text-align:center;"> <strong>ID</strong> </td><td style="text-align:center;"> <strong>Text</strong> </td></tr>
<tr><td style="text-align:center;"> button_B </td><td style="text-align:center;"> Remove C </td></tr>
<tr><td style="text-align:center;"> button_C </td><td style="text-align:center;"> Remove D </td></tr>
<tr><td style="text-align:center;"> button_D </td><td style="text-align:center;"> Remove </td></tr></table>
<p>Notice the mismatch of ID and text? Notice that the last button's <code>#{var.key}</code> evaluated to null? </p>
<p>To understand the problem, it is best to describe a step by step process of how the code works:
</p><ol style="list-style-type:decimal;">
<li class="1">The for each tag is executed and the first iteration (count 0) is begun</li>
<li class="1">The tag creates an <code>IndexedValueExpression</code>. This sub-class of <code>ValueExpression</code>.<ul>
<li class="1u">The expression to get the items is stored (<code>#{bean.items}</code>)</li>
<li class="1u">The index of the for each iteration is stored (<code>0</code>)</li></ul></li>
<li class="1">This <code>IndexedValueExpression</code> is then added to the <code>VariableMapper</code> as the <code>var</code> - item.</li>
<li class="1">The body of the tag is executed</li>
<li class="1">The command button tag is instructed to create or find a component with ID <code>button_A</code>. </li>
<li class="1">The command button component is created with all its attributes.<ul>
<li class="1u">When the component is created, the <code>ValueExpression</code> instances are created</li>
<li class="1u">Each <code>ValueExpression</code> is created with a reference to the <code>FunctionMapper</code> and <code>VariableMapper</code></li></ul></li>
<li class="1">The for each tag proceeds with its execution and processes indexes 1-3</li></ol>
<p>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 <code>button_A</code> was never referenced, and is therefore removed from its parent, the form.</p>
<p>The problem is that once the component is created, the <code>ValueExpression</code> 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 <code>button_B</code> which was found for the first item after item A was removed still has its original <code>ValueExpression</code> for the <code>value</code> attribute. This expression has the variable mapper with the indexed value expression for the <code>var</code> which has index 1. </p>
<p>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.
</p>
<h2>Problem 2 - Component State</h2>
<p>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.</p>
<p>Lets use the above use case with the IDs removed:
</p><pre lang="x-xml"><<span class="xtag">h:form</span>>
<<span class="xtag">c:forEach</span> <span class="xnam">var</span>=<span class="xval">"item"</span> <span class="xnam">items</span>=<span class="xval">"#{bean.items}"</span>>
<<span class="xtag">h:commandButton</span>
<span class="xnam">value</span>=<span class="xval">"Remove #{var.key}"</span>
<span class="xnam">actionListener</span>=<span class="xval">"#{bean.remove}"</span> />
</<span class="xtag">c:forEach</span>>
</<span class="xtag">h:form</span>></pre>
<p>This renders as:</p>
<table><tr><td style="text-align:center;"> <strong>ID</strong> </td><td style="text-align:center;"> <strong>Text</strong> </td></tr>
<tr><td style="text-align:center;"> j_id_id2 </td><td style="text-align:center;"> Remove A </td></tr>
<tr><td style="text-align:center;"> j_id_id2j_id_1 </td><td style="text-align:center;"> Remove B </td></tr>
<tr><td style="text-align:center;"> j_id_id2j_id_2 </td><td style="text-align:center;"> Remove C </td></tr>
<tr><td style="text-align:center;"> j_id_id2j_id_3 </td><td style="text-align:center;"> Remove D </td></tr></table>
<p>When A is removed, since the item key is not used in the ID, the above problem is not witnessed:</p>
<table><tr><td style="text-align:center;"> <strong>ID</strong> </td><td style="text-align:center;"> <strong>Text</strong> </td></tr>
<tr><td style="text-align:center;"> j_id_id2 </td><td style="text-align:center;"> Remove B </td></tr>
<tr><td style="text-align:center;"> j_id_id2j_id_1 </td><td style="text-align:center;"> Remove C </td></tr>
<tr><td style="text-align:center;"> j_id_id2j_id_2 </td><td style="text-align:center;"> Remove D </td></tr></table>
<p>What you will notice is that item B which used component with ID <code>j_id_id2j_id_1</code> is now rendered by component with ID <code>j_id_id2</code>. 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.
</p>
<h2>How could this be addressed?</h2>
<p>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 <code>ValueExpression</code> 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.</p>
<p>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 <code>Map</code> instead of a <code>List</code> or array to be able to lookup the value for the key. Something like:</p>
<pre lang="x-xml"><<span class="xtag">h:form</span>>
<<span class="xtag">c:forEach</span> <span class="xnam">var</span>=<span class="xval">"item"</span> <span class="xnam">keys</span>=<span class="xval">"#{items.keys} items="</span>#{bean.items}">
<<span class="xtag">h:commandButton</span>
<span class="xnam">value</span>=<span class="xval">"Remove #{var.key}"</span>
<span class="xnam">actionListener</span>=<span class="xval">"#{bean.remove}"</span> />
</<span class="xtag">c:forEach</span>>
</<span class="xtag">h:form</span>></pre>
<p>Where keys would be a <code>List</code> or array of serializable objects for keys in the items which would be represented as a <code>Map</code>.
</p>
<h2>Summary</h2>
<p>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.
</p>
</div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com8tag:blogger.com,1999:blog-29717104.post-9171591836529766302008-06-07T09:29:00.002-06:002009-05-01T13:54:56.273-06:00Understanding the dataTable<style type="text/css">
blockquote {
background-color: #FFFFCC;
}
</style>
My blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2008/06/understanding-datatable.html">You can find this article here</a>
<div style="display: none">
<p>The <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/h/dataTable.html"> <code><h:dataTable/></code></a>, although easy for many to understand to use is often not understood in how it actually works. Since my article on <a href="http://andrewfacelets.blogspot.com/2008/03/build-time-vs-render-time.html"> component tree construction and rendering with respect to JSTL</a> seemed to be received pretty well, I have decided to cover how the <code><h:dataTable/></code> works.
</p>
<h2>Table Of Contents</h2>
<ul>
<li class="u"><a href="#looping"> Looping components</a></li>
<li class="u"><a href="#architecture"> General Architecture</a></li>
<li class="u"><a href="#encoding"> Encoding the Children</a></li>
<li class="u"><a href="#var"> Understanding var</a></li>
<li class="u"><a href="#phases"> Other Phases</a></li>
<li class="u"><a href="#clientid"> Understanding Client IDs</a></li>
<li class="u"><a href="#events"> Event Broadcasting</a></li>
<li class="u"><a href="#binding"> Binding</a></li>
<li class="u"><a href="#conclusion"> Conclusion</a></li></ul>
<p><a name="looping"></a></p>
<h2>Looping components</h2>
<p>
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:</p><ul>
<li class="u"><a href="http://myfaces.apache.org/trinidad/index.html"> Apache MyFaces Trinidad</a><ul>
<li class="uu"><a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_iterator.html"> <code><tr:iterator></code></a></li>
<li class="uu"><a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_table.html"> <code><tr:table></code></a></li>
<li class="uu"><a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_tree.html"> <code><tr:tree></code></a></li>
<li class="uu"><a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_treeTable.html"> <code><tr:treeTable></code></a></li></ul></li>
<li class="u"><a href="http://myfaces.apache.org/tomahawk/index.html"> Apache MyFaces Tomahawk</a><ul>
<li class="uu"><a href="http://myfaces.apache.org/tomahawk/tlddoc/t/dataList.html"> <code><t:dataList></code></a></li>
<li class="uu"><a href="http://myfaces.apache.org/tomahawk/tlddoc/t/dataTable.html"> <code><t:dataTable></code></a></li>
<li class="uu"><a href="http://myfaces.apache.org/tomahawk/tlddoc/t/tree2.html"> <code><t:tree2></code></a></li></ul></li>
<li class="u"><a href="https://facelets.dev.java.net/nonav/docs/dev/docbook.html"> Facelets</a><ul>
<li class="uu"><a href="https://facelets.dev.java.net/nonav/docs/dev/docbook.html#template-repeat"> <code><ui:repeat></code></a></li></ul></li>
<li class="u">Etc.</li></ul>
<p>Each of these components, although renders quite different HTML all work using a similar design, modeled by the core <code><h:dataTable/></code>.</p>
<p><a name="architecture"></a></p>
<h2>General Architecture</h2>
<p>
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 <code><h:dataTable/></code> creates an outer <code><TABLE></code> with a <code><TR/></code> for each iteration of the loop. Others like <a href="http://myfaces.apache.org/tomahawk/tlddoc/t/dataList.html"> <code><t:dataList></code></a>, <a href="https://facelets.dev.java.net/nonav/docs/dev/docbook.html#template-repeat"> <code><ui:repeat></code></a> and <a href="http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/tr_iterator.html"> <code><tr:iterator></code></a> produce no HTML usually, so they simply allow one to loop over a set of components for many objects in a model.</p>
<p>Each of these components have <code>value</code> and <code>var</code> attributes, although their names may change slightly from component to component. The <code>value</code> 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 <strong>temporarily</strong>. This variable has a name given by the <code>var</code> attribute. Take for example this code that shows all of the cookies sent to the server in a table in a servlet environment:</p>
<pre lang="x-xml"><<span class="xtag">h:dataTable</span>
<span class="xnam">var</span>=<span class="xval">"_cookie"</span>
<span class="xnam">value</span>=<span class="xval">"#{facesContext.externalContext.request.cookies}"</span>>
<<span class="xtag">h:column</span>>
<<span class="xtag">f:facet</span> <span class="xnam">name</span>=<span class="xval">"header"</span>>
<<span class="xtag">h:outputText</span> <span class="xnam">value</span>=<span class="xval">"Name"</span> />
</<span class="xtag">f:facet</span>>
<<span class="xtag">h:outputText</span> <span class="xnam">value</span>=<span class="xval">"#{_cookie.name}"</span> />
</<span class="xtag">h:column</span>>
<<span class="xtag">h:column</span>>
<<span class="xtag">f:facet</span> <span class="xnam">name</span>=<span class="xval">"header"</span>>
<<span class="xtag">h:outputText</span> <span class="xnam">value</span>=<span class="xval">"Value"</span> />
</<span class="xtag">f:facet</span>>
<<span class="xtag">h:outputText</span> <span class="xnam">value</span>=<span class="xval">"#{_cookie.value}"</span> />
</<span class="xtag">h:column</span>>
</<span class="xtag">h:dataTable</span>></pre>
<p>The <code>value</code> is an array of <code>Cookie</code> objects. The <code>var</code> 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 <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/model/DataModel.html"> DataModel</a>. It then sets the <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/model/DataModel.html#setRowIndex(int)"> <code>rowIndex</code></a> which caused the <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/model/DataModel.html#getRowData()"> <code>rowData</code></a> 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 <code>rows</code> and <code>first</code> attributes). </p>
<p>The most important thing to note is that even though there may be several cookies, there are only ever 4 <code>outputText</code> components (1 in each header and one in each column). </p>
<p><a name="encoding"></a></p>
<h3>Encoding the Children</h3>
<p>What happens to produce multiple <code><TR/></code> elements is that the <code>TableRenderer</code> encodes its children in a loop. Here are the steps of <code>TableRenderer.encodeChildren</code>:</p><ol style="list-style-type:decimal;">
<li class="1">get the first row to be rendered from <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getFirst()"> <code>UIData.getFirst()</code></a></li>
<li class="1">get the number of rows to be rendered from <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getRows()"> <code>UIData.getRows()</code></a></li>
<li class="1">write the <code><TBODY/></code> start tag</li>
<li class="1">loop until the correct number of rows have been rendered<ol style="list-style-type:decimal;">
<li class="11">if <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#isRowAvailable()"> row is not available</a> then stop</li>
<li class="11">render the row, encoding all the children recursively</li></ol></li></ol>
<p><a name="var"></a></p>
<h3>Understanding "var"</h3>
<p>
The <code>var</code> is not controlled by the renderer, but the component, <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html"> <code>UIData</code></a> to be precise. Non-<code>UIData</code> components that loop perform similar logic if designed after the JSF table. The scope of the <code>var</code> is limited to when the <code><t:dataTable/></code> is currently iterating. To be exact, it is available when the <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getRowIndex()"> <code>rowIndex</code></a> is not -1. In the <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#setRowIndex(int)"> <code>UIData.setRowIndex(int)</code></a> 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.</p>
<p>The state is comprised of all the children components that implement <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/EditableValueHolder.html"> EditableValueHolder</a>. So before the row index is changed, <code>UIData</code> saves the <code>value</code>, <code>localValueSet</code>, <code>valid</code> and <code>submittedValue</code> properties for each child below the table and restores any state saved for the new index. This means that only <code>EditableValueHolder</code> components may vary state for different rows. Non-<code>EditableValueHolder</code> 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 <code>var</code>.</p>
<p>The code stores the row data for the current row into the request map using the value of <code>var</code> 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 <code>var</code> 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 <code>var</code> that will not conflict with other request map variables. This is why I always prepend my <code>var</code> values with and underscore.</p>
<blockquote><p><strong>Note:</strong><br/>
The <code>var</code> is only in scope when the <code>UIData</code>'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 <code>UIData</code> with the correct scope, you must set the row index to the desired value, otherwise the data will not be there.</p></blockquote>
<p><a name="phases"></a></p>
<h2>Other Phases</h2>
<p>
The decode, validate and updating processes of the <code><h:dataTable/></code> 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 <code>var</code> and save and restore the states is in <code>UIData</code>, the behavior is shared. </p>
<p><a name="clientid"></a></p>
<h2>Understanding Client IDs</h2>
<p>
You may have noticed that the client IDs of looped components are altered in a table. Take this use case:
</p><pre lang="x-xml"><<span class="xtag">h:dataTable</span>
<span class="xnam">id</span>=<span class="xval">"cookies"</span>
<span class="xnam">var</span>=<span class="xval">"_cookie"</span>
<span class="xnam">value</span>=<span class="xval">"#{facesContext.externalContext.request.cookies}"</span>>
<<span class="xtag">h:column</span>>
<<span class="xtag">h:outputText</span> <span class="xnam">id</span>=<span class="xval">"cookieName"</span> <span class="xnam">value</span>=<span class="xval">"#{_cookie.name}"</span> />
</<span class="xtag">h:column</span>>
</<span class="xtag">h:dataTable</span>>
<<span class="xtag">h:outputText</span> <span class="xnam">id</span>=<span class="xval">"after"</span> <span class="xnam">value</span>=<span class="xval">"After the table"</span> /></pre>
<p>The two <code><h:outputText/></code> 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 <code>UIData</code> component returns a different ID from <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/UIData.html#getClientId(javax.faces.context.FacesContext)"> getClientId</a> when the row index is not -1. The code from the JSF RI (a.k.a. Mojarra) is:
</p><pre lang="x-java"> @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;
}</pre>
<p>As you can see, <code>NamingContainer.SEPARATOR_CHAR + rowIndex</code> 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.</p>
<p><a name="events"></a></p>
<h2>Event Broadcasting</h2>
<p>
When a child of the table is decoded, it decodes correctly due to the client ID. Take for example an <code><h:inputText id="myInputText"/></code> component that is in a table. Using just two rows as an example here is a map of the client IDs:
</p><table><tr><td style="text-align:center;"> <strong>Row Index</strong> </td><td style="text-align:left;"><strong>Client ID</strong> </td></tr>
<tr><td style="text-align:center;"> -1 </td><td style="text-align:left;">myTable:myInputText </td></tr>
<tr><td style="text-align:center;"> 0 </td><td style="text-align:left;">myTable:0:myInputText </td></tr>
<tr><td style="text-align:center;"> 1 </td><td style="text-align:left;">myTable:1:myInputText </td></tr></table>
<p>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. </p>
<p>Now this is great for decoding, but a different mechanism must be used for the queuing and the broadcasting of events. The <code>UIData</code> component wraps all events in a wrapper class that stores the event being queued, the client ID of the <code>UIData</code> component and the current row index. Here is what each property is used for:
</p><dl><dt>Client ID</dt><dd>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.
</dd><dt>Event</dt><dd>The original event that will be unwrapped during broadcast. The wrapper delegates much of its functionality to the wrapped event (like the phase ID).
</dd><dt>Row Index</dt><dd>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.</dd></dl>
<p><a name="binding"></a></p>
<h2>Binding</h2>
<p>
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 <code><h:commandLink action=#{bean.actionMethod}"/></code> 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. </p>
<p>Also since the <code>var</code>'s scope is only valid during iteration, it is not accessible during the construction of the component tree. Therefore and JSP tags or Facelets <code>TagHandler</code>s may not attempt to retrieve row data using the <code>UIData</code> APIs.</p>
<p><a name="conclusion"></a></p>
<h2>Conclusion</h2>
<p>
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 <code>EditableValueHolder</code> 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.</p>
<p>Client IDs and event wrappers are used to ensure that the event model of JSF is not broken by the iteration of the component.</p>
<p>Hopefully this helps you understand looping components better and helps you design better pages as a result. Thank you for reading.</p></div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com3tag:blogger.com,1999:blog-29717104.post-39528212145360171492008-03-18T09:02:00.003-06:002009-05-01T13:56:04.503-06:00Build time vs. render time<style type="text/css">
blockquote.note {
background-color: #FFFFCC;
}
blockquote.note div {
font-weight: bold;
}
</style>
My blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2008/03/build-time-vs-render-time.html">You can find this article here</a>
<div style="display: none">
<h1>Overview</h1>
<p>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.</p>
<h1>The Problem</h1>
<p>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.</p>
<h2>A Background of JSP</h2>
<p>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 <code>System.out.println(...);</code> statements.</p>
<p>Tag libraries enhanced JSP by providing an API to tag authors to write Java code that would not have to be embedded in <% ... %> 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.</p>
<h3>The JSTL</h3>
<p>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 <code>c:if</code> and <code>c:choose</code>, they choose which tag contents to be included in the response or not.</p>
<p>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.</p>
<h2>What JSF Is</h2>
<p>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.</p>
<blockquote class="note">
<div>Note</div>
<p>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.</p>
</blockquote>
<h3>Component Technology</h3>
<p>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.</p>
<blockquote class="note">
<div>Note</div>
<p>A component is simply a Java Object that implements the UIComponent interface, nothing more.</p>
</blockquote>
<p>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 <code>c:forEach</code>).</p>
<blockquote class="note">
<div>Note</div>
<p>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.</p>
</blockquote>
<blockquote class="note">
<div>Note</div>
<p>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 <code>ResponseWriter</code>'s API is designed for XML content.</p>
</blockquote>
<h1>JSF with JSP</h1>
<p>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:</p>
<ol>
<li>Building of the component tree using JSP tags</li>
<li>Rendering of the component tree using the standard JSF lifecycle</li>
</ol>
<h2>Building of the component tree using JSP tags</h2>
<p>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 <code>UIComponentClassicTagBase</code>. The class hierarchy is:</p>
<ul>
<li>java.lang.Object</li>
<ul>
<li>javax.faces.webapp.UIComponentTagBase</li>
<ul>
<li>javax.faces.webapp.UIComponentClassicTagBase</li>
<ul>
<li>javax.faces.webapp.UIComponentELTag</li>
<li>javax.faces.webapp.UIComponentTag</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>The <code>doStartTag</code> method of <code>UIComponentClassicTagBase</code> calls <code>findComponent</code>, which despite its name creates the component (if needed) and calls <code>setProperties</code>. Therefore, the JSF component is created when the start of the JSP tag is processed. The <code>setProperties</code> 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 <code>setProperties</code> 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.</p>
<h2>How JSTL fits in</h2>
<p>Most of the "work" of a component takes place during rendering. For example, the <code>h:dataTable</code> sets up the <code>var</code> 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.</p>
<p>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 <code>var</code> variable of an <code>h:dataTable</code>. Take this code for example:</p>
<blockquote class="largeCode"><p>
<f:view>
<h:dataTable var="_row" value="#{bean.rows}>
<h:column>
<c:choose>
<c:when test="#{_row.editable}">
<h:inputText value="#{_row.value}" />
</c:when>
<c:otherwise>
<h:outputText value="#{_row.value}" />
</c:otherwise>
</c:choose>
</h:column>
</h:dataTable>
</f:view>
</p></blockquote>
<p>Although from the pure XML standpoint this looks valid, it is not. Thinking about what I just said it is a simple problem:</p>
<ol>
<li>Data table component created from the data table JSP tag</li>
<li>Column component created from its JSP tag</li>
<li>The when tag in the choose attempts to evaluate <code>#{_row.editable}</code>
<ul>
<li>Since <code>_row</code> is not bound (yet) in the EL resolver, null is returned<br/>
(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)</li>
<li>Since null is technically false, the <code>outputText</code> is created instead of the <code>inputText</code></li>
</ul>
</li>
<li>The output text component is created by its tag</li>
</ol>
<p>So the page author was probably expecting that the <code>choose</code> 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 <code>inputText</code> component is never created as the <code>when</code> tag will not process its contents if the test fails.</p>
<p>The proper solution is to use JSF functionality and not JSP functionality. To the confusion of JSP developers, there are no <code>c:if</code>, <code>c:choose</code> or <code>c:forEach</code> equivalent components (see the <a href="http://myfaces.apache.org/sandbox/limitRendered.html">Tomahawk Sandbox limitRendered</a> for <code>c:if</code> and <code>c:choose</code> functionality and the <a href="http://myfaces.apache.org/tomahawk/dataList.html">Tomahawk dataList</a> or <a href="http://myfaces.apache.org/trinidad/trinidad-1_2/trinidad-api/tagdoc/tr_iterator.html">Trinidad iterator</a> components for <code>c:forEach</code> type of functionality). Without third party components, the rendered attribute can also work, although it requires more work:</p>
<blockquote class="largeCode"><p>
<f:view>
<h:dataTable var="_row" value="#{bean.rows}>
<h:column>
<h:inputText value="#{_row.value}" rendered="#{_row.editable}" />
<h:outputText value="#{_row.value}" rendered="#{not _row.editable}" />
</h:column>
</h:dataTable>
</f:view>
</p></blockquote>
<p>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.</p>
<h3>When it is okay to use JSP tags with JSF</h3>
<p>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.</p>
<p>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, <b>a JSF component tree should never be altered between having its state saved and when its state is restored</b>. The reason is that this would violate the JSF specification/design. Take for example a <code>c:forEach</code> 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.</p>
<p>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.</p>
<h1>Hey, what about Facelets?</h1>
<p>I did mention that I would talk about facelets, didn't I?</p>
<p>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 <code>TagHandler</code>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.</p>
<h1>Other Blogs</h1>
<p>Here are some other helpful resources on this topic:</p>
<ul>
<li><a href="http://www.ilikespam.com/blog/c:foreach-vs-ui:repeat-in-facelets">c:foreach vs ui:repeat in facelets</a></li>
</ul>
</div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com7tag:blogger.com,1999:blog-29717104.post-24838606049142141292007-09-17T08:48:00.001-06:002009-05-01T13:56:52.008-06:00Trinidad versus Tomahawk component architectureMy blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2007/09/trinidad-versus-tomahawk-component.html">You can find this article here</a>
<div style="display: none">
<p>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.</p>
<p>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.</p>
<h2>Why is Tomahawk a better component development platform?</h2>
<p>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.</p>
<h3>Comparison:</h3>
<p>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:</p>
<div class="code">
// MyComponent comp;
String value = comp.getMyProperty();
value = comp.getAttributes().get("myProperty");
</div>
<p>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.</p>
<p>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.</p>
<h2>Code generation</h2>
<p>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 <b>have</b> 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</p>
<h2>Conclusion</h2>
<p>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.</p>
<h3>To the Trinidad team:</h3>
<p>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.</p>
<p>Since this would break backwards-compatibility, Trinidad's major version could be bumped.</p>
<hr />
<h3>Updates and responses to comments</h3>
<h4>2007-09-17</h4>
<p>Simon,</p>
<p>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.</p>
<p>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.</p><p>Is the efficiency of FacesBean worth the cost of bypassing encapsulation and reducing a component's methods to not much more than a Map<String,Object>?</p>
<p>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.</p>
<p>Instead of using FacesBean, renderers could use the attribute map instead, this would ensure that renderers remain component agnostic. For example:</p>
<div class="code">public void encodeBegin(FacesContext facesContext, UIComponent comp) {
Map<String, Object> attrs = comp.getAttributes();
Renderer delegate = getMyRendererDelegate();
delegate.renderStuff(facesContext, attrs);
}</div>
<p>Or</p>
<div class="code">public void encodeBegin(FacesContext facesContext, UIComponent comp) {
Map<String, Object> attrs = comp.getAttributes();
String styleClass = toString(attrs.get("styleClass"));
}
protected String toString(Object obj) {
return obj == null ? null : obj.toString();
}</div>
<p>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</p>
<p>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.</p>
<p>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.</p>
<h4>2007-09-17</h4>
Adam,
<p>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.</p><p>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.</p><p>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.</p>
<h4>2007-09-17</h4>
<p>Simon,</p>
<p>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.</p>
</div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com5tag:blogger.com,1999:blog-29717104.post-21875995392576840712006-11-18T12:38:00.001-07:002009-05-01T13:57:32.565-06:00Is JSF made for AJAX or does it just "play along"?My blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2006/11/is-jsf-made-for-ajax-or-does-it-just.html">You can find this article here</a>
<div style="display: none">
<p>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.</p>
<p>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)</p>
<h2>Background</h2>
<p>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:</p>
<ul>
<li>AjaxAnywhere</li>
<li>Ajax4Jsf</li>
<li>G4Jsf</li>
<li>Trinidad</li>
<li>jsf-extensions/Avatar</li>
<li>ICEFaces</li>
<li>JBoss-Seam (in the works)</li>
<li>etc.</li>
</ul>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<h2>Enter AJAX</h2>
<p>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).</p>
<h3>The problem</h3>
<p>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!</p>
<p>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 & 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 & 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).</p>
<p>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.</p>
<p><a href="http://weblogs.java.net/blog/jhook/">Jacob Hookom</a> has had some really good insights on this issue:</p>
<ul>
<li><a href="http://weblogs.java.net/blog/jhook/archive/2006/01/experiment_goin_1.html">Experiment: Going Stateless with JSF</a></li>
<li><a href="http://weblogs.java.net/blog/jhook/archive/2006/02/new_feature_for.html">New Feature for JSF 1.2</a></li></ul>
<h2>Is the grass greener?</h2>
<p>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 <a href="http://ajaxian.com/archives/gwt-jsf-g4jsf">G4Jsf</a>, 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.</p>
<p>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.</p>
<p>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.</p>
<h2>What Now?</h2>
<p>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).</p>
<p>Is there something I missed with these JSF AJAX libraries to get around the component tree performance issue?</p>
<p>Please keep the comments to Java based technologies as they apply to JSF, this is not meant to be language war.</p>
<h2>Update: 2007-04-22</h2>
<p>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.</p>
<p>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. </p>
<p>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).</p>
</div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com10tag:blogger.com,1999:blog-29717104.post-1151429308915388262006-06-27T10:54:00.001-06:002009-05-01T13:58:25.061-06:00MyFaces Tree2 - Creating a lazy loading treeMy blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2006/06/myfaces-tree2-creating-lazy-loading.html">You can find this article here</a>
<div style="display: none">
<blockquote>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.</blockquote>
<p>Although the <a href="http://wiki.apache.org/myfaces/Tree2">MyFaces Tree2 WIKI</a> 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.</p>
<p>My approach:<br/>
Use AJAX via <a href="http://ajaxanywhere.sf.net">AjaxAnywhere</a> 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.<p>
<p>My use case was wrapped around a content management solution, so it was file/directory based nodes.</p>
What was needed:
<ul><li>Custom tree node for "directory nodes"</li>
<li>Custom tree nodes for "file nodes" that could be selected</li>
</ul>
<blockquote>Note: this blog will not discuss AJAX and enabling the tree in server side mode, that would be another discussion entirely</blockquote>
<p>
Step 1: create a "lazy loading" tree node that we can extend:</p>
<blockquote class="largeCode">public class BaseTreeNode
implements TreeNode
{
private BaseTreeNode parent;
private String identifier;
private String name;
private String type;
protected List<BaseTreeNode> 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<BaseTreeNode> 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 && !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<BaseTreeNode> loadChildren()
{
return null;
}
}</blockquote>
<p>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.</p>
<p>Step 2: create the directory node (inner class):</p>
<blockquote class="largeCode">public class FolderNode
extends BaseTreeNode
{
FolderNode(TreeModel model, BaseTreeNode parent, String name)
{
super(model, parent, "folder", name, name, false);
}
@Override
protected List<BaseTreeNode> loadChildren()
{
return <Your business code class here>.loadChildren(this);
}
}</blockquote>
<p>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.</p>
<p>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).</p>
<p>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.</p>
<p>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.</p>
<p>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).</p>
<p>FYI, here is the "file" node code:</p>
<blockquote class="largeCode">public class FileNode
extends BaseTreeNode
{
FileNode(TreeModel model, BaseTreeNode parent, String name)
{
super(model, parent, "file", name, name, true);
}
}</blockquote>
The XHTML is as follows:
<blockquote class="largeCode"><aa:zoneJSF id="treeZone">
<my:ajaxTree
value="#{contentMgmtBean.treeModel}"
ajaxZone="treeZone"
var="_node"
clientSideToggle="false"
varNodeToggler="t"
showRootNode="false">
<f:facet name="folder">
<t:panelGroup>
<t:graphicImage
styleClass="treeNodeIcon"
url="#{_node.expanded ?
'/images/contentMgmt/openfolder.gif' :
'/images/contentMgmt/closedfolder.gif'}" />
<t:outputText
styleClass="folderNodeText"
value="#{_node.name}" />
</t:panelGroup>
</f:facet>
<f:facet name="file">
<my:ajaxCommandLink
ajaxZone="treeZone,myResultZone"
actionListener="#{contentMgmtBean.nodeSelected}"
styleClass="fileNodeLink#{
contentMgmtBean.currentFileName eq _node.name ?
' selectedNode' : ''}">
<t:updateActionListener
property="#{contentMgmtBean.currentFileName}"
value="#{_node.name}" />
<t:graphicImage
styleClass="treeNodeIcon"
url="/images/contentMgmt/file.gif" />
<t:outputText
styleClass="fileNodeText"
value="#{_node.name}" />
</ost:ajaxCommandLink>
</f:facet>
</my:ajaxTree>
</aa:zoneJSF>
</blockquote>
<p>Example of using the node as an inner class:</p>
<blockquote class="largeCode">public class BeanClass
{
private TreeModel treeModel;
public List<BaseTreeNode> loadChildren(FolderNode parent)
{
List<BaseTreeNode> children = new ArrayList<BaseTreeNode>();
List<String> folders = ; // load from web service
for (String folder : folders)
children.add(new FolderNode(treeModel, parent, folder));
List<String> 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<BaseTreeNode> loadChildren()
{
return loadChildren(this);
}
}
}</blockquote>
<p><span style="font-weight: bolder; font-size: large">Update</span>
This code has been moved to a jsf-comp component. Go to
<a href="http://sf.net/projects/jsf-comp">http://sf.net/projects/jsf-comp</a>
to download. An example war file is included in the release</p>
© Copyright 2006 - Andrew Robinson.<br/>
Please feel free to use in your applications under the LGPL license (<a href="http://www.gnu.org/licenses/lgpl.html">http://www.gnu.org/licenses/lgpl.html</a>).
</div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com13tag:blogger.com,1999:blog-29717104.post-1150664913953975182006-06-18T14:25:00.001-06:002009-05-01T13:59:09.178-06:00Running actions despite validation errorsMy blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2006/06/running-actions-despite-validation.html">You can find this article here</a>
<div style="display: none">
<p>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.</p>
<p>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.</p>
Table of contents:
<ol>
<li><a href="#first">Immediate</a></li>
<li><a href="#second">Action validation</a></li>
<li><a href="#third">Tomahawk sandbox subForm</a></li>
<li><a href="#forth">Optional validator framework</a></li>
<li><a href="#fifth">New component (solution)</a></li>
</ol>
<p><a name="first">First</a> 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.</p>
<p><a name="second">After that</a>, 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).</p>
<p>The <a name="third">third</a> 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:</p>
<blockquote class="code"><f:form>
<s:subForm id="mainForm">
<-- Other input componenets here -->
<t:commandLink action="#{userBean.addEmail}"
actionFor="dummyForm" />
</subForm>
<s:subForm id="dummyForm" />
</blockquote>
<p>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.</p>
<p><a name"forth">Forth</a> 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.</p>
<p>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.</p>
<p>My <a name="fifth">fifth</a> 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.</p>
<p>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.</p>
<p>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:</p>
<blockquote class="largeCode">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 && 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];
}
}
</blockquote>
The usage in my XHTML file was simple:
<blockquote class="code"><f:form>
<my:validationAction>
<t:commandLink action="#{userBean.addEmail}" />
</my:validationAction>
</f:form>
</blockquote>
<p>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.</p>
© Copyright 2006 - Andrew Robinson.<br/>
Please feel free to use in your applications under the LGPL license <br/>(http://www.gnu.org/licenses/lgpl.html).<br/>
<table>
<thead>
<tr>
<th colspan="2">
Updates/Change log
</th>
</tr>
<tr>
<th>
Date
</th>
<th>
Description
</th>
</tr>
</thead>
<tbody>
<tr>
<td>2007.03.07</td>
<td>Fixed some of the code in the component that was a result of pasting the code into the blog incorrectly.</td>
</tr>
<tr>
<td>2007.04.22</td>
<td>Reformatting of HTML in blog.</td>
</tr>
</tbody>
</table>
</div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com12tag:blogger.com,1999:blog-29717104.post-1150313426446898922006-06-14T12:34:00.003-06:002009-05-01T13:59:50.802-06:00Creating composite controls with JSF and faceletsMy blog has moved, please update your links.
<a href="http://drewdev.blogspot.com/2006/06/creating-composite-controls-with-jsf.html">You can find this article here</a>
<div style="display: none">
<p>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.</p>
<p>With that said <a href="https://facelets.dev.java.net">Facelets</a> 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.</p>
For example:<br/>
Snippet from taglib.xml:
<blockquote class="code"><tag>
<tag-name>test</tag-name>
<source>tags/testTag.xhtml</source>
</tag></blockquote>
Usage in an XHTML file:
<blockquote class="code"><my:test actionListener="#{myBean.doSomething}" /></blockquote>
User Tag file:
<blockquote class="code"><ui:composition>
<h:commandButton value="Click Me" actionListener="#{actionListener}" />
</ui:composition></blockquote>
<p>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 "ought" to be created.</p>
<p>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:</p>
<ol>
<li>Create a tag handler with component support</li>
<li>Create a new value expression that returns method expressions</li>
</ol>
<h3>Creating a value expression that is a method expression</h3>
<p>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 "#{myBean.doSomething}" to be interpreted as a method instead of a property called "getDoSomething"</p>
<p>The code below may need some work to be more "correct", but it does work:</p>
<blockquote class="code">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);
}
}
</blockquote>
<p>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.</p>
<p>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:</p>
<blockquote class="code">public class CompositeControlHandler
extends TagHandler
{
private final TagAttribute methodBindings;
private ComponentHandler componentHandler;
/**
* @param config
*/
public CompositeControlHandler(TagConfig config)
{
super(config);
methodBindings = getAttribute("methodBindings");
}
// TODO...
}
</blockquote>
<p>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:</p>
<blockquote class="code">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;
</blockquote>
Example from above:
<blockquote class="code">actionListener=void javax.faces.event.ActionEvent;
</blockquote>
<p>So now that we have a way to specify what attributes are now methods, we need to do the work.</p>Steps:
<ol>
<li>Parse the attribute</li>
<li>For each attribute, see if the value is "bound" in the current variable mapper</li>
<li>If bound, create a new method expression from the configuration information</li>
<li>Hide the initial variable with the method expression</li>
</ol>
<p>The resultant code is as follows:</p>
<blockquote class="code">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 < 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;
}
}
}</blockquote>
<p>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).</p>
<p>The code isn't much different, so I will show it in its entirety here:</p>
<blockquote class="code">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 < 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;
}
}
}</blockquote>
<p>Now we need to register this in a taglib.xml so that we can use it:</p>
<blockquote class="code"><tag>
<tag-name>compositeControl</tag-name>
<handler-class>mypackage.CompositeControlHandler</handler-class>
</tag></blockquote>
Now that it is registered, lets use it. The XHTML file that uses the tag hasn't changed:
<blockquote class="code"><my:test actionListener="#{myBean.doSomething}" /></blockquote>
The user tag does look different, but not that much:
<blockquote class="code"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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">
<body>
<ui:composition>
<my:compositeControl
id="#{id}"
methodBindings="action=java.lang.String;
actionListener=void javax.faces.event.ActionEvent;">
<ui:debug />
<h:commandButton value="Click me"
actionListener="#{actionListener}"
action="#{action}" />
</my:compositeControl>
</ui:composition>
</body>
</html></blockquote>
That should be enough to get you going.
© Copyright 2006 - Andrew Robinson.
Please feel free to use in your applications under the LGPL license (<a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">http://www.gnu.org/licenses/lgpl.html</a>).
</div>Anonymoushttp://www.blogger.com/profile/12230997086550680222noreply@blogger.com15