Showing posts with label JSF. Show all posts
Showing posts with label JSF. Show all posts

Wednesday, January 4, 2012

Component scope

It is often confusing to users what it means by having a JSF component be "in scope," especially in JSF 2. JSF is processed by a set of phases, each one usually iterates the component tree, acting upon each component in turn. Some components, like the h:dataTable, perform stamping.

Note, for more information on stamping, please see my blog on tables.

When a component is being processed, the EL context may be altered. For example, the data table injects "var" and "varStatus" variables into the request scope. This also means that when the table is not being processed, these variables are either not available, or point to another value.

This is what I mean by a component being "in scope," that it is currently being processed by the JSF lifecycle or JSF APIs in a manner congruent with the JSF specification for working with components.

How a component enters scope

A component can enter scope one of three ways:

  1. The JSF lifecycle is being run. This will be the result of calls from methods on the component:
    • processDecodes
    • processValidators
    • processUpdates
    • processSaveState
    • processRestoreState
    • broadcast
  2. During an invokeOnComponent callback
  3. During a visitTree callback

At any other time, it may not be valid to be interacting with the component. Take for example, using Oracle ADF components, an input text component inside of an iterator:

<af:iterator var="item" value="#{bean.items}">
  <af:inputText value="#{item.value}" binding="#{bean.inputText}" />
</af:iterator>

Now consider this Java code for the bean:

private RichInputText _inputText;

public RichInputText getInputText()
{
  return _inputText;
}

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

public Object getValue()
{
  return _inputText == null ? null : _inputText.getValue();
}

Should code call the bean's getValue() method, what is the outcome? Well that is indeed the problem. Before the JSF view is built, the value will be null as the component has not been bound yet. Between JSF phases, it will also be null because #{item} will not be present in the EL context.

As this example shows, the attributes and behavior of the component in question change based on what component is currently being operated on. What makes this even more of an issue, is component frameworks that setup and tear down contexts. For example, Oracle ADF faces has a base component class called a oracle.adf.view.rich.component.fragment.ContextSwitchingComponent. When a component is processing its JSF lifecycle, or one of its children is being called back via a visitTree or invokeOnComponent call, the setupContext method has been run. If one of these components is accessed through code, and the context has not been set up yet, unreliable results may occur, or even exceptions may be thrown. One use case is of the ADF page template component. By using context switching, this component alters the EL context so that facets in the page with the <af:pageTemplate /> tag are executed in the EL context they were defined in, and the components inside the page template definition are executed within the context of the page template definition file.

Note that JSF 2 has a compound component like the ADF page template, but I am not sure how it handles EL context resultion.

It is therefore, never a good idea to call methods or evaluate attributes on JSF components unless the caller is sure that the component being accessed is currently in scope. Here is another example:

<af:iterator var="item" value="#{bean.items}">
  <af:pageTemplate viewId="template.jspx" item="#{item}">
    <f:facet name="center">
      <af:outputText id="facetText" value="#{item.itemValue}" />
    </f:facet>
  </f:pageTemplate>
</af:iterator>

Page definition:

...
<af:pageTemplateDef var="attrs">
  <af:xmlContent>
    <component xmlns="http://xmlns.oracle.com/adf/faces/rich/component">
      <description>This component lays out an entire page.</description>
      <facet>
        <description>The center content.</description>
        <facet-name>center</facet-name>
      </facet>
      <attribute>
        <description>the item.</description>
        <attribute-name>item</attribute-name>
        <attribute-class>com.mycompany.MyItem</attribute-class>
      </attribute>
    </component>
  </af:xmlContent>
  <af:iterator var="item" value="#{item.innerItems}">
    <af:facetRef facetName="center"/>
    <af:outputText id="templateText" value="#{item.itemValue}" />
  </af:iterator>
</af:pageTemplateDef>

This is a very simplified example, but it illustrates the question, what does #{item.itemValue}" evaluate to? In the facet, this should be the item from the bean's items collection, as shown with the output text with id "facetText". Inside the page template, the value should be the item from the inner items collection of the item passed into the page template, show by the output text with the id "templateText". Depending on when this EL is evaluated, different values will be returned. Therefore, is is crucial, that in order to evaluate the RichOutputText.getValue() method, that the call is made while that component is "in scope," or "in context."

Putting a component into context

Components are automatically put into context when they are being validated, updated, broadcasting events, rendering, etc. Sometimes it is necessary to interact with a component outside of its context. For example, perhaps you have backing bean code that wishes to get the input text value. This may be done by knowing a component's client ID, and using the visitTree method. Here is an example:

public void performAction(ActionEvent evt)
{
  String clientId = "template1:table1:0:firstNameInputText";
  FacesContext facesContext = FacesContext.getCurrentInstance();
  VisitContext visitContext = VisitContext.createVisitContext(facesContext,
    Collections.singleton(clientId), EnumSet.of(SKIP_UNRENDERED));
  GetFirstNameCallback callback = new GetFirstNameCallback();
  facesContext.getViewRoot().visitTree(visitContext, callback);

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

private static class GetFirstNameCallback
  implements VisitCallback
{
  private String _firstName;

  public String getFirstName()
  {
    return _firstName;
  }

  public VisitResult visit(
    VisitContext visitContext,
    UIComponent  target)
  {
    RichInputText inputText = (RichInputText)target;
    _firstName = (String)inputText.getValue();
    return VisitResult.COMPLETE;
  }
}

Here the code illustrates how to access the input text value for a component in the first row of a table.

Summary

Due to the fact that EL is contextual, it is important that any EL based functionality is only accessed in the correct context for that EL. As such, JSF developers should use caution when interacting with components via their Java APIs. Using visit tree should always be considered when trying to access properties from a component in order to ensure that the expected EL context has been setup when the component attempts to access its data. Failing to do so may cause issues with your programs, and even data contamination.

Sunday, August 10, 2008

c:forEach with JSF could ruin your day

Last week, a co-worker of mine at Oracle was attempting to use a forEach 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.

The JSTL <c:forEach/> 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 <c:forEach/> loop except for basic usage only.

Use Case

For the illustration of the problem with the <c:forEach/> 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 items attribute. For the first, consider the following requirements:

  • For each loop required, JSF stamped iteration components cannot be used (like JSP tags that include a page)
  • Ajax used to partially render the page
  • Id's of components must be tied to the item in the loop to allow actions

Problem 1 - static EL

A simple example can be used to show the problem:

<h:form>
  <c:forEach var="item" items="#{bean.items}">
    <h:commandButton
      id="button_${var.key}"
      value="Remove #{var.key}"
      actionListener="#{bean.remove}" />
  </c:forEach>
</h:form>

Take for example a list of "A", "B", "C" and "D". The buttons render as:

ID Text
button_A Remove A
button_B Remove B
button_C Remove C
button_D Remove D

Now should the user click "Remove A", the managed bean removes the value from the items list. The result is:

ID Text
button_B Remove C
button_C Remove D
button_D Remove

Notice the mismatch of ID and text? Notice that the last button's #{var.key} evaluated to null?

To understand the problem, it is best to describe a step by step process of how the code works:

  1. The for each tag is executed and the first iteration (count 0) is begun
  2. The tag creates an IndexedValueExpression. This sub-class of ValueExpression.
    • The expression to get the items is stored (#{bean.items})
    • The index of the for each iteration is stored (0)
  3. This IndexedValueExpression is then added to the VariableMapper as the var - item.
  4. The body of the tag is executed
  5. The command button tag is instructed to create or find a component with ID button_A.
  6. The command button component is created with all its attributes.
    • When the component is created, the ValueExpression instances are created
    • Each ValueExpression is created with a reference to the FunctionMapper and VariableMapper
  7. The for each tag proceeds with its execution and processes indexes 1-3

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 button_A was never referenced, and is therefore removed from its parent, the form.

The problem is that once the component is created, the ValueExpression 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 button_B which was found for the first item after item A was removed still has its original ValueExpression for the value attribute. This expression has the variable mapper with the indexed value expression for the var which has index 1.

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.

Problem 2 - Component State

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.

Lets use the above use case with the IDs removed:

<h:form>
  <c:forEach var="item" items="#{bean.items}">
    <h:commandButton
      value="Remove #{var.key}"
      actionListener="#{bean.remove}" />
  </c:forEach>
</h:form>

This renders as:

ID Text
j_id_id2 Remove A
j_id_id2j_id_1 Remove B
j_id_id2j_id_2 Remove C
j_id_id2j_id_3 Remove D

When A is removed, since the item key is not used in the ID, the above problem is not witnessed:

ID Text
j_id_id2 Remove B
j_id_id2j_id_1 Remove C
j_id_id2j_id_2 Remove D

What you will notice is that item B which used component with ID j_id_id2j_id_1 is now rendered by component with ID j_id_id2. 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.

How could this be addressed?

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 ValueExpression 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.

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 Map instead of a List or array to be able to lookup the value for the key. Something like:

<h:form>
  <c:forEach var="item" keys="#{items.keys} items="#{bean.items}">
    <h:commandButton
      value="Remove #{var.key}"
      actionListener="#{bean.remove}" />
  </c:forEach>
</h:form>

Where keys would be a List or array of serializable objects for keys in the items which would be represented as a Map.

Summary

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.

Update 2012-10-03

Partial fix to be available as part of Trinidad. My blog on the enhancement to the Trinidad for each tag.

Saturday, June 7, 2008

Understanding the dataTable

The <h:dataTable/>, although easy for many to understand to use is often not understood in how it actually works. Since my article on component tree construction and rendering with respect to JSTL seemed to be received pretty well, I have decided to cover how the <h:dataTable/> works.

Table Of Contents

Looping components

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:

Each of these components, although renders quite different HTML all work using a similar design, modeled by the core <h:dataTable/>.

General Architecture

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 <h:dataTable/> creates an outer <TABLE> with a <TR/> for each iteration of the loop. Others like <t:dataList>, <ui:repeat> and <tr:iterator> produce no HTML usually, so they simply allow one to loop over a set of components for many objects in a model.

Each of these components have value and var attributes, although their names may change slightly from component to component. The value 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 temporarily. This variable has a name given by the var attribute. Take for example this code that shows all of the cookies sent to the server in a table in a servlet environment:

<h:dataTable
  var="_cookie"
  value="#{facesContext.externalContext.request.cookies}">
  <h:column>
    <f:facet name="header">
      <h:outputText value="Name" />
    </f:facet>
    <h:outputText value="#{_cookie.name}" />
  </h:column>
  <h:column>
    <f:facet name="header">
      <h:outputText value="Value" />
    </f:facet>
    <h:outputText value="#{_cookie.value}" />
  </h:column>
</h:dataTable>

The value is an array of Cookie objects. The var 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 DataModel. It then sets the rowIndex which caused the rowData 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 rows and first attributes).

The most important thing to note is that even though there may be several cookies, there are only ever 4 outputText components (1 in each header and one in each column).

Encoding the Children

What happens to produce multiple <TR/> elements is that the TableRenderer encodes its children in a loop. Here are the steps of TableRenderer.encodeChildren:

  1. get the first row to be rendered from UIData.getFirst()
  2. get the number of rows to be rendered from UIData.getRows()
  3. write the <TBODY/> start tag
  4. loop until the correct number of rows have been rendered
    1. if row is not available then stop
    2. render the row, encoding all the children recursively

Understanding "var"

The var is not controlled by the renderer, but the component, UIData to be precise. Non-UIData components that loop perform similar logic if designed after the JSF table. The scope of the var is limited to when the <t:dataTable/> is currently iterating. To be exact, it is available when the rowIndex is not -1. In the UIData.setRowIndex(int) 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.

The state is comprised of all the children components that implement EditableValueHolder. So before the row index is changed, UIData saves the value, localValueSet, valid and submittedValue properties for each child below the table and restores any state saved for the new index. This means that only EditableValueHolder components may vary state for different rows. Non-EditableValueHolder 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 var.

The code stores the row data for the current row into the request map using the value of var 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 var 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 var that will not conflict with other request map variables. This is why I always prepend my var values with and underscore.

Note:
The var is only in scope when the UIData'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 UIData with the correct scope, you must set the row index to the desired value, otherwise the data will not be there.

Other Phases

The decode, validate and updating processes of the <h:dataTable/> 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 var and save and restore the states is in UIData, the behavior is shared.

Understanding Client IDs

You may have noticed that the client IDs of looped components are altered in a table. Take this use case:

<h:dataTable
  id="cookies"
  var="_cookie"
  value="#{facesContext.externalContext.request.cookies}">
  <h:column>
    <h:outputText id="cookieName" value="#{_cookie.name}" />
  </h:column>
</h:dataTable>
<h:outputText id="after" value="After the table" />

The two <h:outputText/> 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 UIData component returns a different ID from getClientId when the row index is not -1. The code from the JSF RI (a.k.a. Mojarra) is:

    @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;
    }

As you can see, NamingContainer.SEPARATOR_CHAR + rowIndex 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.

Update: 2007-06-22
Just today, I found an "interesting feature" of UIData. After looking into Jira ticket TRINIDAD-1514, I found that UIComponentBase in both the RI as well as MyFaces caches client IDs. This means that a client ID is not re-generated per-stamp. What happens is the UIData has a kluge to surf all of the components recursively of the UIData, setting its ID to the same value. The setId() on UIComponentBase clears the cached client ID, even if the ID is not actually changed by the function. It is an interesting piece of code (a.k.a. ugly hack). I thought it would be good to mention it here.

Event Broadcasting

When a child of the table is decoded, it decodes correctly due to the client ID. Take for example an <h:inputText id="myInputText"/> component that is in a table. Using just two rows as an example here is a map of the client IDs:

Row Index Client ID
-1 myTable:myInputText
0 myTable:0:myInputText
1 myTable:1:myInputText

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.

Now this is great for decoding, but a different mechanism must be used for the queuing and the broadcasting of events. The UIData component wraps all events in a wrapper class that stores the event being queued, the client ID of the UIData component and the current row index. Here is what each property is used for:

Client ID
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.
Event
The original event that will be unwrapped during broadcast. The wrapper delegates much of its functionality to the wrapped event (like the phase ID).
Row Index
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.

Binding

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 <h:commandLink action=#{bean.actionMethod}"/> 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.

Also since the var's scope is only valid during iteration, it is not accessible during the construction of the component tree. Therefore and JSP tags or Facelets TagHandlers may not attempt to retrieve row data using the UIData APIs.

Conclusion

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 EditableValueHolder 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.

Client IDs and event wrappers are used to ensure that the event model of JSF is not broken by the iteration of the component.

Hopefully this helps you understand looping components better and helps you design better pages as a result. Thank you for reading.

Tuesday, March 18, 2008

Build time vs. render time

Overview

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.

The Problem

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.

A Background of JSP

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 System.out.println(...); statements.

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.

The JSTL

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 c:if and c:choose, they choose which tag contents to be included in the response or not.

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.

What JSF Is

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.

Note

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.

Component Technology

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.

Note

A component is simply a Java Object that implements the UIComponent interface, nothing more.

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 c:forEach).

Note

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.

Note

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 ResponseWriter's API is designed for XML content.

JSF with JSP

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:

  1. Building of the component tree using JSP tags
  2. Rendering of the component tree using the standard JSF lifecycle

Building of the component tree using JSP tags

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 UIComponentClassicTagBase. The class hierarchy is:

  • java.lang.Object
    • javax.faces.webapp.UIComponentTagBase
      • javax.faces.webapp.UIComponentClassicTagBase
        • javax.faces.webapp.UIComponentELTag
        • javax.faces.webapp.UIComponentTag

The doStartTag method of UIComponentClassicTagBase calls findComponent, which despite its name creates the component (if needed) and calls setProperties. Therefore, the JSF component is created when the start of the JSP tag is processed. The setProperties 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 setProperties 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.

How JSTL fits in

Most of the "work" of a component takes place during rendering. For example, the h:dataTable sets up the var 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.

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 var variable of an h:dataTable. Take this code for example:

<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>

Although from the pure XML standpoint this looks valid, it is not. Thinking about what I just said it is a simple problem:

  1. Data table component created from the data table JSP tag
  2. Column component created from its JSP tag
  3. The when tag in the choose attempts to evaluate #{_row.editable}
    • Since _row is not bound (yet) in the EL resolver, null is returned
      (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)
    • Since null is technically false, the outputText is created instead of the inputText
  4. The output text component is created by its tag

So the page author was probably expecting that the choose 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 inputText component is never created as the when tag will not process its contents if the test fails.

The proper solution is to use JSF functionality and not JSP functionality. To the confusion of JSP developers, there are no c:if, c:choose or c:forEach equivalent components (see the Tomahawk Sandbox limitRendered for c:if and c:choose functionality and the Tomahawk dataList or Trinidad iterator components for c:forEach type of functionality). Without third party components, the rendered attribute can also work, although it requires more work:

<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>

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.

When it is okay to use JSP tags with JSF

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.

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, a JSF component tree should never be altered between having its state saved and when its state is restored. The reason is that this would violate the JSF specification/design. Take for example a c:forEach 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.

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.

Hey, what about Facelets?

I did mention that I would talk about facelets, didn't I?

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 TagHandlers. 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.

Other Blogs

Here are some other helpful resources on this topic:

Saturday, November 18, 2006

Is JSF made for AJAX or does it just "play along"?

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.

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)

Background

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:

  • AjaxAnywhere
  • Ajax4Jsf
  • G4Jsf
  • Trinidad
  • jsf-extensions/Avatar
  • ICEFaces
  • JBoss-Seam (in the works)
  • etc.

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.

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.

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.

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.

Enter AJAX

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).

The problem

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!

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).

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.

Jacob Hookom has had some really good insights on this issue:

Is the grass greener?

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 G4Jsf, 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.

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.

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.

What Now?

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).

Is there something I missed with these JSF AJAX libraries to get around the component tree performance issue?

Please keep the comments to Java based technologies as they apply to JSF, this is not meant to be language war.

Update: 2007-04-22

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.

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.

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).

Sunday, June 18, 2006

Running actions despite validation errors

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.

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.

Table of contents:
  1. Immediate
  2. Action validation
  3. Tomahawk sandbox subForm
  4. Optional validator framework
  5. New component (solution)

First 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.

After that, 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).

The third 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:

<f:form> <s:subForm id="mainForm"> <-- Other input componenets here --> <t:commandLink action="#{userBean.addEmail}" actionFor="dummyForm" /> </subForm> <s:subForm id="dummyForm" />

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.

Forth 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.

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.

My fifth 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.

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.

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:

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]; } }
The usage in my XHTML file was simple:
<f:form> <my:validationAction> <t:commandLink action="#{userBean.addEmail}" /> </my:validationAction> </f:form>

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.

© Copyright 2006 - Andrew Robinson.
Please feel free to use in your applications under the LGPL license
(http://www.gnu.org/licenses/lgpl.html).
Updates/Change log
Date Description
2007.03.07 Fixed some of the code in the component that was a result of pasting the code into the blog incorrectly.
2007.04.22 Reformatting of HTML in blog.

Wednesday, June 14, 2006

Creating composite controls with JSF and facelets

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.

With that said Facelets 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.

For example:
Snippet from taglib.xml:
<tag> <tag-name>test</tag-name> <source>tags/testTag.xhtml</source> </tag>
Usage in an XHTML file:
<my:test actionListener="#{myBean.doSomething}" />
User Tag file:
<ui:composition> <h:commandButton value="Click Me" actionListener="#{actionListener}" /> </ui:composition>

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.

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:

  1. Create a tag handler with component support
  2. Create a new value expression that returns method expressions

Creating a value expression that is a method expression

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"

The code below may need some work to be more "correct", but it does work:

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); } }

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.

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:

public class CompositeControlHandler extends TagHandler { private final TagAttribute methodBindings; private ComponentHandler componentHandler; /** * @param config */ public CompositeControlHandler(TagConfig config) { super(config); methodBindings = getAttribute("methodBindings"); } // TODO... }

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:

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;
Example from above:
actionListener=void javax.faces.event.ActionEvent;

So now that we have a way to specify what attributes are now methods, we need to do the work.

Steps:
  1. Parse the attribute
  2. For each attribute, see if the value is "bound" in the current variable mapper
  3. If bound, create a new method expression from the configuration information
  4. Hide the initial variable with the method expression

The resultant code is as follows:

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; } } }

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).

The code isn't much different, so I will show it in its entirety here:

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; } } }

Now we need to register this in a taglib.xml so that we can use it:

<tag> <tag-name>compositeControl</tag-name> <handler-class>mypackage.CompositeControlHandler</handler-class> </tag>
Now that it is registered, lets use it. The XHTML file that uses the tag hasn't changed:
<my:test actionListener="#{myBean.doSomething}" />
The user tag does look different, but not that much:
<!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>
That should be enough to get you going. © Copyright 2006 - Andrew Robinson. Please feel free to use in your applications under the LGPL license (http://www.gnu.org/licenses/lgpl.html).