Categorie: Java

What’s new in JSF 2.2?

22 January 2012

JSF 2.2 is currently in its early stages of development, and originally had an anticipated release of the final draft of the spec in Q4 2011 (see Jsf 2 2-bof, slide 3 and JSR 344: JavaServer Faces 2.2). This date slipped, but we might still see the actual release somewhere in the first half of 2012.

So what’s going to be in 2.2? The JSR gives an overview of ideas, but explicitly makes the reservation that not all of those will be in the final spec. So, another source worth looking at is the actual trunk of the reference implementation and its associated implementation JIRA as well as that of the public specification JIRA.

In this post I’ll try to highlight some items from that activity that I found interesting. Note that all of this is preliminary and just reflects the activity in the trunk, not what is absolutely promised to be in the final JSF 2.2 specification. Of course, if there’s a lot of activity and commits for some item, there’s a rather high chance that it will indeed end up in the spec.

Contents

GET Support


View Actions (spec issue 758) (mentioned in JSR)

JSF 2.0 made GET requests a first class citizen in JSF and brought it almost on par with the existing POST support. Just as after a post-back, request values from a GET request can be bound to a model and converters and validators can be applied to that binding.

However, JSF 2.0 didn’t specify an associated action method. A preRenderView event listener can be used instead and that actually does work for a lot of use-cases, but it’s not at the same level as normal action methods that are invoked after a POST request. Users have to manually interact with the NavigationHandler and since the listener is invoked before every rendering, users have to programmatically check if the request was a GET request or a post-back.

View actions are going to allow the same kind of action methods that are used for post-backs to be useable via a new metadata element called <f:viewAction>. The Seam 3 component with the same name was an important inspiration for this.

An additional advantage of a view action is that it can be processed before the entire component tree is being build. Only the meta data needs to be present, which is normally build separately from the rest of the tree.

The feature is discussed in more detail together with sample code at: New JavaServer Faces 2.2 Feature: The viewAction Component

A very simple example:

1
2
3
<f:metadata>    
    <f:viewAction action="#{someBean.someAction}" />
</f:metadata>

Commits for this feature have been done between 16/jun/11 and 18/aug/11.

AJAX


Queue control for AJAX requests (spec issue 1050)

The standard AJAX support in JSF causes AJAX requests to be queued client-side to make sure a page has only 1 such request in transit at the same time.

This is normally beneficial, as it prevents the server from being overloaded and responses arriving out of order. Typical features here are specifying the maximum size of the queue or the amount of time a request is allowed to sit waiting in the queue.

However, JSF lacked those features. Werner Punz wrote about this recently: Apache MyFaces jsf.js queue control.

JSF will add support for controlling the queue by means of a delay attribute on the <f:ajax> tag. This attribute takes a value in milliseconds and signals that if multiple requests arrive within this delay period, only the most recent one is sent to the server. The default is 300 milliseconds, but the special value of none can be specified to disable this mechanism.

Commits for this feature have been done on 10/jun/11 and the associated issue has been marked as resolved.


AJAX file upload component (spec issue 802) (mentioned in JSR)

Having a (AJAX) file upload component in JSF goes back a long time. There is much existing discussion on this issue, and many component libraries have in the mean time implemented something themselves.

An AJAX variant is even more difficult, not in the least since it’s not directly supported in HTML. There’s an iframe based trick available, but this by itself does not work directly with JSF. To support this, changes are required to the mechanism that triggers a JSF request/response cycle.

A prerequisite to an AJAX file upload mechanism is having a standard file upload in JSF. For this a separate issue was created: Non-Ajax File Upload. Interesting here is that this implementation is based on Servlet 3.0 multipart support, like e.g. this implementation by my co-worker Bauke. This means among other that the venerable FacesServlet is now annotated with the @MultipartConfig annotation and that JSF now requires Servlet 3.0.

The standard file upload component can be used on a view as follows:

1
2
3
4
5
6
7
<h:form prependId="false" enctype="multipart/form-data">
 
    <!-- The new regular file upload component -->
    <h:inputFile id="fileUpload" value="#{someBean.file}" />
 
    <h:commandButton value="Upload" />
</h:form>

Commits for the sub-issue have been done on 15/dec/11.


Injection / Annotations


Injection in all JSF artifacts (spec issue 763) (mentioned in JSR)

In JSF 2.1, relatively few JSF artifacts are injection targets for EJB (@EJB, @Resource), CDI (@Inject) or JSF’s native injection mechanism. Basically only managed beans (backing beans) are injection targets.

This poses a problem for e.g. converters and validators, which not rarely need an EJB service to do their work. For instance, an incoming user ID from a GET request might needs to be converted to a User instance via the Stateless EJB UserService. There are some workarounds for this as outlined in this excellent guide from my co-worker Bauke, but they ain’t pretty.

In JSF 2.2 injection will be possible in converters, validators, components, behaviors and much more artifacts.

Commits for this feature have been done between 27/aug/11 and 31/oct/11 and the associated issue had been marked as resolved, but on 11/jan/12 an additional commit was done that changed how the InjectionProvider is internally obtained by the FactoryFinder.


Facelets ResourceResolver can be declared via annotation (spec issue 1038)

In Facelets it has always been possible to let users provide a hook to influence the way that Facelets loads template files. This is done via a ResourceResolver that users can register in web.xml via the environment parameter javax.faces.FACELETS_RESOURCE_RESOLVER.

With such a resolver, users can let Facelets load templates from the classpath or from any location that is expressible via a URL.

The web.xml mechanism however pre-dates the time that Facelets was officially part of JSF itself and it of course requires the presence of such a web.xml file. Since Facelets is now officially part of JSF and there is a strong trend going to make XML optional in favor of annotations, the Facelets resource resolver has now gotten an official annotation in the JSF spec:

@FaceletsResourceResolver.

The presence of that annotation on a class automatically registers it as a Facelets resource resolver. If a resolver is specified in both XML and via an annotation, the XML overrides the annotation as per the usual Java EE conventions. If multiple annotated classes are found, the first one encountered is used and a warning is logged.

Commits for this feature have been done between 06/oct/11 and 12/oct/11 and the associated issue has been marked as resolved.

Security / Type-safety


Cross Site Request Forgery protection (spec issue 869) (mentioned in JSR)

Cross Site Request Forgery is an attack that lets users unknowingly do a request to a site where they are supposed to be logged-in, that has some side-effect that is most likely in some way beneficial to the attacker. GET based requests are most obvious here, but POST requests are just as vulnerable.

JSF seems to have some implicit protection against this when state is saved on the server, since a post-back must contain a valid javax.faces.ViewState hidden parameter. Contrary to earlier versions, this value seems sufficiently random in modern JSF implementations.

Nevertheless, JSF 2.2 will contain additional/even stricter protection against this. Among others client state encryption is now on by default and there’s a token parameter for protection of non-postback views.

Commits for this feature have been done between 13/sep/11 and 21/sep/11.


More thorough type checking for composite component attributes (spec issue 745)

In JSF 2.1, it’s not always easy to defer the exact type of a value expression bound to an attribute of a composite component, if said expression resolves to null. Finding the right type just by asking ElResolver is complicated by the fact that ELResolver#getType is supposed to return the most general type that is accepted by the corresponding ELResolver#setValue. It’s also not always equal to getValue().getClass() as explained by the javadoc.

In JSF 2.1, CompositeComponentAttributesELResolver#getType returned null when asked for the type, since it’s a read only resolver.

For JSF 2.2 this is replaced with an algorithm that first checks if the base is an ExpressionEvalMap and if so simply gets the value expression from that and asks it for its type. Then the metadata for the composite component is consulted to see if there’s a type being set for the given attribute (this corresponds to the type attribute on the cc:attribute tag). Finally, if a type is found via the metadata it’s only used if the type obtained from the value expression is either null, or if the metadata type is more specific (narrower).

Commits for this feature have been done between 20/jul/11 and 10/aug/11.

Java API


FaceletFactory in the standard API (spec issue 611)

JSF has a facility for obtaining factories for various things via the FactoryFinder. Even though Facelets is a standard part of JSF since 2.0, the FaceletFactory could not be obtained this way as it was an implementation detail.

In JSF 2.2, the status of Facelets as a default technology within JSF has been given another boost by making this factory obtainable from the FactoryFinder and moving it to the API part of JSF.

Commits for this feature have been done on 15/sep/11 and the associated issue has been marked as resolved.


Instantiating composite component in Java (spec issue 599)

JSF 2.0 introduced the concept of the composite component: a component that is created via an .xhtml template instead of Java code. Even though the composite component is defined in .xhtml, it’s a first class component and ends up in the component tree as a Java component.

Up till now however there wasn’t any official API to instantiate a composite component as a Java instance via user code. So when building a component tree programmatically (see e.g. Authoring JSF pages in pure Java), incorporating those composite components was challenging to say the least.

JSF 2.2 will provide an explicit API for this.

Commits for this feature have been done between 02/oct/11 and 04/oct/11 and the associated issue has been marked as resolved.


Support for the Collection interface in UIData (spec issue 479) (mentioned in JSR)

From the beginning of JSF, the UIData component (known from e.g. <h:dataTable>) only realistically supports the List, native array and JSF specific DataModel as input for its value binding*. This means other collection types always have to be expressed as any of these types. While this is not particular difficult, it’s a tedious thing to do and makes the code more verbose.

This issue has a rather long history, but it’s now finally addressed.

JSF 2.2 will introduce a javax.faces.model.CollectionDataModel in which UIData wraps an incoming value if it’s of type Collection. Collection is one of the last types being checked, so if the incoming value is a List the ListDataModel takes precedence.

The following are now the supported types:

  • null (becomes empty list)
  • javax.faces.model.DataModel
  • java.util.List
  • java.lang.Object[]
  • java.sql.ResultSet
  • javax.servlet.jsp.jstl.sql.Result
  • java.util.Collection new!
  • java.lang.Object (becomes ScalarDataModel)

Commits for this feature have been done on 31/jan/12 and the associated issue has been marked as resolved.

* java.sql.ResultSet and javax.servlet.jsp.jstl.sql.Result are officially also supported, but it seems usage of those are rather rare in practice. Also, only DataModel is internally supported, other types are automatically adapted into a DataModel.

Lifecycle


Restoring view scope before view is build (spec issue 787)

In JSF 2.0 a new scope called the view scope was introduced. The life-time of this scope is coupled to that of the view state associated with the component tree for a given view. As such it’s easy to just store the data in this scope along with the view state and restore it whenever view state is restored, which happens right after the view has been build.

However, for some advanced usages it’s more convenient to have the view scope restored before the view is build again. As a very contrived example, the bean Intro from the code shown in Single class pure Java JSF application could not be view scoped, since the view scope doesn’t exists at the time the view needs to be build.

Disentangling the view scope from the general view state data actually has other benefits as well, e.g. users could provide alternative handlers for the view scope, something which is not possible or at least very difficult and not portable at the moment.

Currently a new method (UIViewRoot#restoreViewScopeState(FacesContext context, Object state)) to restore only ViewScope has been committed. A separate effort is planned for JSF 2.2 to also create the corresponding saveViewScopeState, but as of yet nothing has been committed for that.

Commits for this feature have been done between 9/jun/11 and 27/jul/11 and the associated issue has been marked as resolved.


System events for The Flash (spec issue 766)

JSF 2 introduced the concept of system events, which are events that can be fired by arbitrary objects at arbitrary points during the request processing lifecycle.

In the current version JSF 2.1 there are some 16 events defined, e.g. PostAddToViewEvent, PostConstructViewMapEvent, PreRenderViewEvent, PreValidateEvent, etc.

JSF 2.2 will fire 4 additional events specifically for usage with The Flash. These are:

  1. PostKeepFlashValueEvent – Fired when a value is kept in The Flash
  2. PostPutFlashValueEvent – Fired when a value is stored in The Flash
  3. PreClearFlashEvent – Fired before The Flash is cleared
  4. PreRemoveFlashValueEvent – Fired when a value is removed from the Flash

Commits for this feature have been done between 28/oct/11 and 31/oct/11.


Publish PostRestoreStateEvent (spec issue 1061)

Normally system events in JSF are fired/published via the Application#publishEvent API.

However in JSF 2.1 and before, PostRestoreStateEvent has been an exception to this rule. The problem is that this event must be delivered to all UIComponents. Requiring the use of the publish API for this is sub-optimal with respect to memory requirements, since it would also require every component to return a list with itself as a listener when UIComponent.getListenersForEventClass() is called.

Earlier versions of JSF therefor delivered the event directly to the components using a tree traversal, but this meant it was not possible to install any listeners for this event.

In JSF 2.2 this problem was solved by simply doing both the event publishing (without making UIComponents default listeners) AND doing the traditional tree traversal. In Mojarra, the event is published first and then the tree traversal starts.

Commits for this feature have been done on 15/dec/11.


Mandate tree visiting for partial state saving (spec issue 1028)

In order to implement the partial state saving feature of JSF, an implementation must somehow look at all components in the component tree and ask them for their (partial) state.

The exact way in which this is done was implementation specific in JSF 2.1 and earlier. Mojarra used a tree visiting algorithm for this, while MyFaces used a so-called “facets + children” traversal.

The differences between those two are somewhat technical, but one of them is that tree visiting allows the algorithm for the actual traversal to be plugged-in (strategy pattern), while the “facets + children” traversal doesn’t allow this (the code accesses the list of children of a component directly and iterates over it).

Another major difference is that tree visiting is “in context” (parent component can set up a context/scope before its children are visited), while “facets + children” traversals just follow a ‘dumb’ pointer structure.

Finally, tree visits have the ability to visit “virtual components” created by iterating components like UIData. (for a typical JSF data table, there is no component per row in the tree, but the UIData creates this illusion by swapping state in and out for each row).

For state saving, this are somewhat conflicting properties. Setting up a context and doing iterating over virtual children is unwanted, but influencing the traversal can be important. JSF 2.1 introduced the IS_SAVING_STATE and SKIP_ITERATION hints, which can undo the unwanted effects, while keeping the ability to influence the traversal.

In JSF 2.2, tree visiting will now be mandated for partial state saving. StateManager#saveView and StateManager#restoreView have been deprecated in favor of methods with the same name in StateManagementStrategy, for which implementations are now required to use the visit API (UIComponent#visitTree), e.g. as-in the simplified example:

1
2
3
4
5
6
7
8
9
10
11
viewRoot.visitTree(visitContext, new VisitCallback() {
    public VisitResult visit(VisitContext context, UIComponent target) {       
        if (!target.isTransient()) {          
            savedState.put(
                target.getClientId(context.getFacesContext()),
                target.saveState(context.getFacesContext())
            );
        }        
        return ACCEPT;
    }
});

(This is a rather advanced feature that the average JSF application developer will not likely come in contact with.)

Commits for this feature have been done on 22/dec/11.

Components


Component modification management (spec issue 984)

In JSF, components can introduce variables in a kind of “component scope” or “component context”. The var attribute of iterating components like UIData or UIRepeat is a well known example of this. E.g.

1
2
3
4
5
<ui:repeat value="#{someBean.items}" var="item">
    <!-- item is in scope here -->
</ui:repeat>
 
<!-- item no longer in scope -->

In JSF 2.1 and before there is no explicit API that components can use to manage this context. This is potentially troublesome for components that need to do a full tree visit within a clean context.

To assist with managing this context, JSF 2.2 will introduce a ComponentModificationManager that can be obtained via a call to FacesContext#getComponentModificationManager

Although details are scarce at the moment (only an API draft has been committed), it’s possible the API might be used by components as follows:

1
2
3
4
5
6
7
8
9
10
public boolean visitTree(VisitContext visitContext, VisitCallback callback) {
    ComponentModificationManager manager = visitContext.getFacesContext().getComponentModificationManager();
 
    ComponentModification modifications = manager.suspend(visitContext.getFacesContext());
    try {
        return super.visitTree(visitContext, callback);
    } finally {
        manager.resume(visitContext.getFacesContext(), modifications);
    }
}

(This is a rather advanced feature that the average JSF application developer will not likely come in contact with.)

Commits for this feature have been done on 16/dec/11.

XML configuration


Case insensitivity for state saving method (spec issue 1010)

In JSF one can set whether state is saved on the server or on the client via the context parameter javax.faces.STATE_SAVING_METHOD in web.xml which can be set to “server” or “client”. The values had to be used exactly as given. Using “Client” or “CLIENT” would actually result in server state saving being used. As of JSF 2.2 the value is made case insensitive, so those preferring to use “Client” can now do so.

Commits for this feature have been done on 26/may/11 and the associated issue has been marked as resolved.

Standards compliance


Using only name attribute for view state field (spec issue 220)

For keeping track of state associated with forms, JSF implementations write a hidden input field in each form that’s used on a page.

In JSF 1.2 this field was standardized and the specification demanded that both the id and name attributes were set to javax.faces.ViewState*.

The rule however breaks “W3C XHTML 1.0 Transitional” and above standards compliance. Namely, per that standard the id attribute should be globally unique within a document. If the JSF spec mandates that it should always have a fixed value, it clearly can’t be unique if multiple forms are being used on a single page.

Very early on, Mojarra introduced the parameter com.sun.faces.enableViewStateIdRendering, that when set to false simply omitted rendering the id attribute (thus leaving only the name present). Since this is an implementation specific parameter, not all third party libraries necessarily take its effects into account.

Therefor from JSF 2.2 on only the name attribute is mandated and JSF 2.2 compatible libraries should no longer assume anything about an id attribute being available. In addition, Mojarra has removed the com.sun.faces.enableViewStateIdRendering parameter completely, so setting this explicitly to true will not bring the id attribute back.

Commits for this feature have been done on 30/jan/12 and the associated issue has been marked as resolved.

*In addition the spec strongly recommends, though doesn’t enforce, that the value of this input field is difficult to predict in order to prevent cross site scripting attacks, see Cross Site Request Forgery protection for more details.


That’s it for now! I’ll periodically update this page when new information comes in.

Keep in mind that there are quite some interesting other things under discussion or even in development for possible inclusion in JSF 2.2. Such development is only currently taking place outside of the JSF trunk, which is the focus of this article. For instance see the discussion about a Window-id which is prototyped in MyFaces/CODI where a proposal is being setup as well, or the one about a multi-templating system (skinning), which is prototyped by lamine ba and mentioned by spec lead Ed Burns in an interview (among with several other interesting things, like HTML5 support).

Arjan Tijms

Easily disable sorting in PrimeFaces 3′s DataTable

16 January 2012

PrimeFaces provides a convenient and easy to use sorting facility for its DataTable. Together with Facelets, this facility allows us to create re-usable columns that are natural sortable by default. E.g.:

1
2
3
4
5
6
7
8
9
<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:p="http://primefaces.org/ui"
>
    <p:column headerText="#{headerText}" sortBy="#{value}">
        <h:outputText id="#{id}" value="#{value}" />
    </p:column>    
</ui:composition>

Such a column can be used on a page inside a DataTable as follows:

1
<my:sortableColumn id="foo" value="#{someBean.someValue}" />

The problem

The above is only a simple example, and real-life usage can be more complex with e.g. default styles and cell editing capabilities added. With such complex tags, it might be desirable to turn off sorting for certain columns programmatically. By default this does not seem to be possible in PrimeFaces. Setting the value attribute in the above example to null or the empty string via an expression prevents sorting, but still renders the sorting icon.

The reason for this is that the PrimeFaces renderer (org.primefaces.component.datatable.DataTableRenderer) checks for the presence of a value expression to determine whether the icon should be rendered, regardless of whether this expression evaluates to something non-empty. So nothing you pass into the value attribute of the above showed tag can make the value expression itself null, nor can any extra attribute accomplish this in the tag’s definition.

Custom helper tag

One solution is to build a simple helper tag that takes a parameter and based on that sets the value expression of its parent component to null. This tag can be nested inside a column. Taking it one step further, we can nest the tag inside a table and programmatically disable sorting on all columns. The following shows the implementation of such a tag:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ColumnSorterDisabler extends TagHandler {
 
    public ColumnSorterDisabler(TagConfig config) {
        super(config);
    }
 
    @Override
    public void apply(FaceletContext ctx, UIComponent parent) throws IOException {
        Boolean disableSorting = getRequiredAttribute("disableSorting").getBoolean(ctx);
        if (disableSorting) {
            if (parent instanceof Column) {
                parent.setValueExpression("sortBy", null);
            } else if (parent instanceof DataTable) {
                for (UIComponent child : parent.getChildren()) {
                    if (child instanceof Column) {
                        child.setValueExpression("sortBy", null);
                    }
                }
            }
        }        
    }    
}

After declaring this in a *-taglib.xml, we can use it as follows inside a Facelets tag:

1
2
3
4
5
6
7
8
9
10
11
<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:p="http://primefaces.org/ui"
>
    <my:columnSorterDisabler disableSorting="#{disableSorting}" />
 
    <p:column headerText="#{headerText}" sortBy="#{value}">
        <h:outputText id="#{id}" value="#{value}" />
    </p:column>    
</ui:composition>

We can now disable sorting on a per-column basis as follows:

1
<my:sortableColumn id="foo" value="#{someBean.someValue}" disableSorting="true" />

or for an entire table:

1
2
3
4
5
<p:dataTable value="#{someBean.someValues}" var="something">
    <my:sortableColumn id="foo" value="#{something.foo}" />
    <my:sortableColumn id="bar" value="#{something.bar}" />
    <my:columnSorterDisabler disableSorting="true" />
</p:dataTable>

One caveat to remember, TagHandlers exist only at ‘build-time’, so when using expressions to do the disabling the data these point to has to be available during build-time.

The f:attributes tag

Another solution, contributed by my co-worker Bauke Scholtz, is taking advantage of the <f:attribute> tag. This tag does the same thing as an actual tag attribute, but contrary to an actual attribute this one can be conditionally excluded using <c:if>. In that case the implementation of our re-usable column becomes this:

1
2
3
4
5
6
7
8
9
10
11
12
<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:p="http://primefaces.org/ui"
>
    <p:column headerText="#{headerText}">
        <c:if test="#{empty sortable or sortable}">
            <f:attribute name="sortBy" value="#{value}"/>
        </c:if>
        <h:outputText id="#{id}" value="#{value}" />
    </p:column>    
</ui:composition>

Notice how the tag attribute sortBy has been replaced by a child tag. This approach is really convenient since it simply uses JSF’s build-in functionality. To disable sorting for all columns at once, the helper tag based approach is still useful though. Note that just like the helper tag, a <f:attribute> tag only exists at build-time, so here too only data that’s available during that time can be used.

Arjan Tijms

Passing action methods into Facelets tags

6 January 2012

The problem

JSF, via Facelets, has various mechanisms to easily reuse view content. One of those is the Facelets tag, which allows one to reuse markup and/or components.

One notorious problem with these Facelets tags is that you can’t directly pass action methods (method expressions) into them. There’s a workaround where you break the expression into two parts, the base (which should be a value expression) and the name of the method as a plain string. Inside the tag these two are then combined again, e.g. via the array notation syntax. See e.g.

Another approach is to create a small helper tag that converts the value expression in some way into a method expression. There have been a couple of implementations of this idea:

Finding a solution

In this blog I would like to present another variant on the tag handler idea, which doesn’t require nesting the content and also doesn’t parse any embedded EL expression manually. It supports EL parameters provided by the calling view. It’s not perfect however, since it does not support parameters being passed into the method from the target component (e.g. an ActionEvent for an actionListener).

The idea is to wrap the value expression (which represents the original method expression passed into the Facelets tag) inside a custom method expression. This method expression simply gets the value from the embedded value expression, which as “side-effect” executes this method.

The resulting method expression has to be stored somewhere. The request scope would be an option, but then it would be directly available outside the Facelets tag, which isn’t a good example of encapsulation.

An alternative is the javax.el.VariableMapper, a “magic” little thing that is able to scope value expressions to the duration of a Facelets tag (it’s magical since remember that the tag doesn’t exist any more after the component tree has been build). This however requires a value expresion again, so in an odd twist we wrap the method expression that we just created in a value expression again.

So, how can this work? Wasn’t the entire point of this exercise to go to a method expression? Well, as it turns out a value expression can be accepted wherever a method expression is required, iff this value expression directly returns a method expression.

E.g. the Apache EL implementation’s org.apache.el.parser.AstIdentifier contains the following code fragment that accomplishes this:

141
142
143
144
145
146
147
148
149
150
151
152
153
154
// case A: ValueExpression exists, getValue which must
// be a MethodExpression
VariableMapper varMapper = ctx.getVariableMapper();
ValueExpression ve = null;
if (varMapper != null) {
    ve = varMapper.resolveVariable(this.image);
    if (ve != null) {
        obj = ve.getValue(ctx);
    }
}
// (case B omitted)
if (obj instanceof MethodExpression) {
    return (MethodExpression) obj;
}

Code

Without further ado, here’s the code for the TagHandler that implements all the wrapping:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class MethodParamHandler extends TagHandler {
 
    private final TagAttribute name;
    private final TagAttribute value;
 
    public MethodParamHandler(TagConfig config) {
        super(config);
        this.name = this.getRequiredAttribute("name");
        this.value = this.getRequiredAttribute("value");
    }
 
    public void apply(FaceletContext ctx, UIComponent parent) throws IOException {
        String nameStr = name.getValue(ctx);
 
        // The original value expression we get inside the Facelets tag, that's actually the method expression passed-in by the user.
        ValueExpression valueExpression = value.getValueExpression(ctx, Object.class);
 
        // A method expression that wraps the value expression and uses its own invoke method to get the value from the wrapped expression.
        MethodExpression methodExpression = new MethodExpressionValueExpressionAdapter(valueExpression);
 
        // Using the variable mapper so the expression is scoped to the body of the Facelets tag. Since the variable mapper only accepts
        // value expressions, we once again wrap it by a value expression that directly returns the method expression.
        ctx.getVariableMapper().setVariable(nameStr, ctx.getExpressionFactory().createValueExpression(methodExpression, MethodExpression.class));    
    }
 
}

The rather trivial adapter that wraps the value expression is shown below. The main method of interest here is invoke(). Note how unfortunately the params parameter has to be ignored.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class MethodExpressionValueExpressionAdapter extends MethodExpression {
 
    private static final long serialVersionUID = 1L;
 
    private final ValueExpression valueExpression;
 
    public MethodExpressionValueExpressionAdapter(ValueExpression valueExpression) {
        this.valueExpression = valueExpression;
    }
 
    @Override
    public Object invoke(ELContext context, Object[] params) {
        return valueExpression.getValue(context);
    }
 
    @Override
    public MethodInfo getMethodInfo(ELContext context) {                
        return new MethodInfo(null, valueExpression.getExpectedType(), null);
    }
 
    @Override
    public boolean isLiteralText() {
        return false;
    }
 
    @Override
    public int hashCode() {
        return valueExpression.hashCode();
    }
 
    @Override
    public String getExpressionString() {
        return valueExpression.getExpressionString();
    }
 
    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
 
        if (obj instanceof MethodExpressionValueExpressionAdapter) {
            return ((MethodExpressionValueExpressionAdapter)obj).getValueExpression().equals(valueExpression);
        }
 
        return false;
    }
 
    public ValueExpression getValueExpression() {
        return valueExpression;
    }
}

The tag handler has to be registered in a *-taglib.xml file, e.g.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<tag>
    <tag-name>methodParam</tag-name>
    <handler-class>com.example.MethodParamHandler</handler-class>
    <attribute>
        <name>name</name>
        <required>true</required>
        <type>java.lang.String</type>
    </attribute>
    <attribute>
        <name>value</name>
        <required>true</required>
        <type>java.lang.String</type>
    </attribute>
</tag>

Using the tag handler

So the above takes care of implementing the converting tag handler. Let’s take a look at how we would use this.

Suppose we have a Facelets tag in the following using-view fragment, where the action attribute binds to a method in a backing bean taking an EL parameter:

1
2
3
<p:dataTable id="table" value="#{someBean.someValues}" var="someValue">
    <my:deleteActionColumn action="#{someBean.delete(someValue)}" update="table" />
</p:dataTable>

The tag could then be defined as shown below. The interesting bit is the <my:methodParam> tag, which converts the value expression “action” to the method expression “actionMethod”. The tag can be placed at many locations, but reasonable choices would be as the first child of the root or directly above the component using it. I choose the latter here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<ui:composition
    xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:my="http://example.com/my"
>
    <p:column styleClass="some_style">
 
        <my:methodParam name="actionMethod" value="#{action}"/>
 
        <p:commandLink id="someId" action="#{actionMethod}" process="@this" update="#{update}">
            <h:graphicImage value="/icons/delete.png" alt="#{i18n['something.delete']}" title="#{i18n['something.delete.tooltip']}" width="15" height="15" />
        </p:commandLink>
    </p:column>
 
</ui:composition>

This Facelets tag too again has to be explicitly declared in a *-taglib.xml, e.g.:

1
2
3
4
5
6
7
8
<tag>
    <tag-name>deleteActionColumn</tag-name>
    <source>faces/tags/deleteActionColumn.xhtml</source>
    <attribute>			
        <name>action</name>        
        <type>javax.el.MethodExpression</type>
    </attribute>
</tag>

Any other alternatives?

At first sight the composite component mechanism would seem to be an alternative, as it explicitly supports passing in method references. However, the composite component isn’t a true substitute for Facelets tags. Namely, it inserts a parent component in the tree instead of simply its content. This doesn’t work for tables, panel groups, and all other kinds of components that require children of a specific type or in a specific order to be present.

You can sometimes do some magic with composite components by using the componentType attribute (see e.g. JSF composite component binding to custom UIComponent), but this only gets you so far and sometimes you really simply need the raw body of a tag to be inserted into the using page.

Another alternative solution, arguably the one and only Real Solution™, is having this fixed by Facelets. Indeed, many years ago there was an issue created for this at the Facelets JIRA: http://java.net/jira/browse/FACELETS-263 with a similar issue even having a patch submitted for it: http://java.net/jira/browse/FACELETS-273. Unfortunately, neither of those issues ever got resolved.

Hopefully the alternative solution provided here is useful for those situations where the existing workarounds are not completely satisfactory. Do note again that the solution presented here is also not ideal, but seems to work nicely in a rather straightforward way for action methods that don’t use framework provided parameters, but can optionally take user supplied EL parameters.

Arjan Tijms

Automatic to-Object conversion in JSF selectOneMenu & Co.

21 December 2011

When creating a web UI, there is often the need to let a user make a selection from e.g. a drop-down. The items in such a drop-down are not rarely backed by domain objects. Since these items in the HTML rendering are just simple character identifiers, we need some way to encode the object version of an item to this simple character identifier (its string representation) and back again.

A well established pattern in JSF is the following:

1
2
3
<selectOneMenu value="#{bean.selectedUser}" converter="#{userConverter}">
    <selectItems value="#{bean.selectableUsers}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

With userConverter defined as something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ManagedBean(name="userConverter")
public class UserConverter implements Converter {
 
    @EJB
    private UserDAO userDAO;
 
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return userDAO.getById(Long.valueOf(value));
    }
 
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return ((User) value).getId().toString();
    }
}

(note that the converter implementation is overly simplified, in practice null checks and checks for “String value” representing a number would be needed)

This is functional, but in its full form not really convenient to program nor efficient. Upon every post back, there will be a call to the DAO to convert the string representation of an item back to its Object form. When no caching is used or the object isn’t in the cache, this will likely result in a call to a back-end database, which is never a positive contribution to the overall performance of a page. It gets worse when there are more of such conversions being done and it can go through the roof when we have e.g. editable tables where each row contains multiple drop-downs. A table with only 10 rows and 4 drop-downs might result in 40 separate calls to the back-end being done.

But is using a DAO here really needed?

After all, after the converter does its work, JSF checks whether the Object is equal to any of the Objects in the collection that was used to render the drop-down. In other words, the target Object is already there! And it must be there by definition, since without it being present validation will simply never pass.

So, by taking advantage of this already present collection we can prevent the DAO calls. The only question is, how do we get to this from a converter? A simple way is to use a parameter of some kind and provide it with a binding to this collection. This is however not really DRY, as it means we have to bind to the same collection twice right after each other (once for the selectItems, once for the converter parameter). Additionally, we still have to iterate over this and need custom code that knows to which property of the Object we need to compare the String value. For instance, for our User object we need to convert the String value to a Long first and then compare it with the Id property of each instance.

Another approach that I would like to present here is basically emulating how a UIDataTable detects on which row a user did some action. After the post back it iterates over the data that was used to render the table in the same way again. This will cause the same IDs to be generated as in the original rendering. The ID of the component that is posted back is compared to the newly generated one and when they match iteration stops and we know the row.

In this case, after the post back we’ll iterate over all select item values, convert these to their string representation and compare that to the ‘to-be-converted’ string value. If they match, the unconverted object is the one we’re after and we return that. For iterating over the select item values, I took advantage of a private utility class that’s in Mojarra: com.sun.faces.renderkit.SelectItemsIterator (for a proof of concept, I just copied it since it’s package private).

The implementation is done via a Converter base class from which user code can inherit. That way, only a getAsString method needs to be implemented:

1
2
3
4
5
6
7
@ManagedBean(name="userConverter")
public class UserConverter extends SelectItemsBaseConverter {
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return ((User) value).getId().toString();
    }
}

The base class is implemented as follows:

1
2
3
4
5
6
public abstract class SelectItemsBaseConverter implements Converter {
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {        
        return SelectItemsUtils.findValueByStringConversion(context, component, value, this);    
    }    
}

And the SelectItemsUtils class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public final class SelectItemsUtils {
 
    private SelectItemsUtils() {}
 
    public static Object findValueByStringConversion(FacesContext context, UIComponent component, String value, Converter converter) {
        return findValueByStringConversion(context, component, new SelectItemsIterator(context, component), value, converter);        
    }
 
    private static Object findValueByStringConversion(FacesContext context, UIComponent component, Iterator<SelectItem> items, String value, Converter converter) {
        while (items.hasNext()) {
            SelectItem item = items.next();
            if (item instanceof SelectItemGroup) {
                SelectItem subitems[] = ((SelectItemGroup) item).getSelectItems();
                if (!isEmpty(subitems)) {
                    Object object = findValueByStringConversion(context, component, new ArrayIterator(subitems), value, converter);
                    if (object != null) {
                        return object;
                    }
                }
            } else if (!item.isNoSelectionOption() && value.equals(converter.getAsString(context, component, item.getValue()))) {
                return item.getValue();
            }
        }        
        return null;
    }
 
    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;    
    }
 
    /**
     * This class is based on Mojarra version
     */
    static class ArrayIterator implements Iterator<SelectItem> {
 
        public ArrayIterator(SelectItem items[]) {
            this.items = items;
        }
 
        private SelectItem items[];
        private int index = 0;
 
        public boolean hasNext() {
            return (index < items.length);
        }
 
        public SelectItem next() {
            try {
                return (items[index++]);
            }
            catch (IndexOutOfBoundsException e) {
                throw new NoSuchElementException();
            }
        }
 
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}

The source of the Mojarra SelectItemsIterator can be found here, MyFaces seems to have a similar implementation here, but I did not test that one yet. PrimeFaces also has something like this (see org.primefaces.util.ComponentUtils#createSelectItems).

A custom selectOneMenu, selectManyListbox etc could even go a step further and should be able to do this without the need for a converter at all. Combined with an extended selectItems tag, it could look like this:

1
2
3
<selectOneMenu value="#{bean.selectedUser}">
    <selectItems value="#{bean.selectableUsers}" var="user" itemValue="#{user}" itemValueAsString="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

In this hypothetical example, we could even simplify stuff further by setting itemValue by default to var, so it would then look like this:

1
2
3
<h:selectOneMenu value="#{bean.selectedUser}">
    <f:selectItems value="#{bean.selectableUsers}" var="user" itemValueAsString="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

Implementing this might be the topic for a next article. For now I'll hope the converter based approach is useful.

Arjan Tijms

Try-with-resources in JDK7 without scoped declarations

26 September 2011

A handy new feature in JDK7 is the try-with-resources statement. This statement is meant to eliminate a lot of the boilerplate code required for managing InputStreams and OutputStreams. Say for example, that I would want to copy the contents of an InputStream to an OutputStream. This would require the following code only to manage the in- and output stream:

InputStream in = createInputStream();
try {
   OutputStream out = createOutputStream();
   try {
      /* Copy data here */
   } finally {
      try {
         out.close();
      } catch(IOException e) {
         //Prevent this exception from suppressing actual exception
      }
   }
} finally {
   try {
      in.close();
   } catch(IOException e) {
      //Prevent this exception from suppressing actual exception
   }
}

Using the new try-with-resources statement, the above code can be rewritten as the following:

try (InputStream in = createInputStream(); OutputStream out =
      createOutputStream()) {
   /* Copy data here */
}

The InputStream and OutputStream are automatically closed at the end of the try-with-resources block. If an exception is thrown during the main block and then again during the closing of one (or both) of the streams, the exception on the close operation is added to the original exception as a suppressed exception, so no exceptions are swallowed silently anymore. The try-with-resources blocks are also not limited to be used for in- and output streams, but can be used on any object that implements the AutoCloseable interface.

There is one minor disadvantage to the try-with-resource statement, it is required to define the variable that refers to the object to be closed within the brackets after the try. For example, if you have a method that receives an InputStream as a parameter, the Java compiler would not allow you to do this:

public void readData(InputStream in) {
   try(in) {
      int input;
      while((input = in.read()) >=0) {
         //Use input here
      }
   }
}

The above code would produce a compiler error as no variable has been defined between the brackets of the try-with-resources statement. I would propose the following workaround for this situation:

public void readData(InputStream in) {
   try(InputStream autoCloseableInputStream = in) {
      int input;
      while((input = in.read()) >=0) {
         //Use input here
      }
   }
}

 


This code does compile and the stream is automatically closed at the end of the try block. Since the autoCloseableInputStream and in variables refer to the exact same object, it is not necessary to actually use the autoCloseableInputStream variable in the code. Using a name like autoCloseableInputStream makes it clear that this variable is only defined in order to be able to use the try-with-resources statement.

Single class pure Java JSF application

18 September 2011

In my previous blog entry, Authoring JSF pages in pure Java, it was explained how to set up a JSF based web application using nothing but pure Java. No XML based templating (Facelets) was required and the view was build purely programmatically.

I got one remark though that the example code did used expression language (EL) to patch some of the parts together. Although EL is really convenient, as it provides a way to point to a (nested) method on a scoped object, it’s not regular type-safe Java.

Luckily, the Java component API of JSF doesn’t only use EL based ValueExpressions and MethodExpressions, but also allows regular Java types to be set as listeners and values. This is demonstrated in the code below. While at it, I’ve done away with the separate backing bean for this example and let the same class that defines the page handle the action event.

The result is a pure Java, xml-less, EL-less, config-less, single class JSF application [phew]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@ManagedBean
public class Intro implements Page, ActionListener {
 
    private HtmlOutputText message;
 
    @Override
    public void buildView(FacesContext context, UIViewRoot root) throws IOException {
 
        List<UIComponent> rootChildren = root.getChildren();
 
        UIOutput output = new UIOutput();
        output.setValue("&lt;html xmlns=\"http://www.w3.org/1999/xhtml\">");                
        rootChildren.add(output);
 
        HtmlBody body = new HtmlBody();
        rootChildren.add(body);
 
        HtmlForm form = new HtmlForm();
        body.getChildren().add(form);
 
        message = new HtmlOutputText();
        form.getChildren().add(message);
 
        HtmlCommandButton actionButton = new HtmlCommandButton();
        actionButton.addActionListener(this);
        actionButton.setValue("Do action");
        form.getChildren().add(actionButton);
 
        output = new UIOutput();
        output.setValue("&lt;/html>");
        rootChildren.add(output);
    }
 
    @Override
    public void processAction(ActionEvent event) throws AbortProcessingException {
        message.setValue("hello, world");
    }    
}

To run this on Glassfish, only this class and the small (8,980 bytes) javavdl.jar library are required:

After requesting localhost:8080/demo/intro.jsf, a single button will be shown. The message “hello, world” will be displayed when this button is clicked.

Interesting to note perhaps is that the components themselves only exist for the duration of the request and after every post-back the component tree will be re-created. State set on the components during buildView will be marked as the so-called initial state and will typically not be taken into account by JSF’s state saving mechanism. Since only the HtmlCommandButton in the example code references the Page instance after this buildView it will effectively have request scope.

The java based vdl is still rather simple, so it’s still just a proof of concept. I’ve planned some enhancements that I’ll work on soon if time permits (e.g. perhaps support for scopes other than request scope without using EL). Stay tuned!

Arjan Tijms

Authoring JSF pages in pure Java

12 September 2011

JSF is well known as a server side web framework to build a web application’s UI with the help of components. For the overwhelming majority of users those components are represented by the tags one uses to compose a page, be it via JSP or Facelets.

The following is a typical example of a page authored with Facelets:

1
2
3
4
5
6
7
8
9
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">    
    <h:body>   
       #{backingBean.hello}   
        <h:form>      
            <h:inputText value="#{backingBean.name}" />                    
            <h:commandButton value="Say Hello" action="#{backingBean.sayHello}" />
        </h:form>        
    </h:body>
</html>

This may give the impression that JSF components *are* the tags shown above, and thus that JSF is necessarily about tags and XML. That is however not true.

JSF has always had a clear separation between the technology used to author pages (the so-called view description language) and the actual API to create components and compose them together into a component tree. This API is a Java API that even in the very first days of JSF had no knowledge whatsoever about JSP or tags. The strict separation allowed alternative view declaration languages like Facelets to be created and eventually be promoted to the default VDL, without needing to change the underlying JSF core framework.

Other view declaration languages have been created as well. One notable example is a concept based on JavaFX, in which a JSF page would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var x = 0;
var bindVal = "Hello";
 
function init(){
   FxPage{
      content : [
         FxForm{
                content : [
                    FxOutputLabel{
                        value : bind bindVal
                    },
                    FxCommandButton{
                        value : "Button"
                        actionListener : function() : String{
                            bindVal = "Hello {x++}";
                            return null;
                        }
                    }
                ]
            }
        ]
    }
}

See: JavaFX as JSF VDL (View Description Language)?

As it appears, the API to create components and compose a component tree is pretty accessible by itself. It could theoretically be used directly to author pages instead of solely being used as an API for VDL implementations. The problem however is that it’s not clear how to actually start doing that. One trick is to use dynamic tree manipulation and add components in a PreRenderView event on an otherwise empty page.

Another way is to create a minimal VDL implementation. As a proof of concept, that’s what I did. With such a thing it’s possible to create a JSF application completely in Java. No Facelets or JSP files, and following Minimal 3-tier Java EE app, without any XML config, no web.xml or faces-config.xml is required either. There doesn’t even have to be a WEB-INF or WebContent directory in the project.

The following shows a JSF page being defined in pure Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Intro implements Page {
 
    @Override
    public void buildView(FacesContext context, UIViewRoot root) throws IOException {
 
        ELContext elContext = context.getELContext();
        ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory();
 
        List<UIComponent> rootChildren = root.getChildren();
 
        UIOutput output = new UIOutput();
        output.setValue("&lt;html xmlns=\"http://www.w3.org/1999/xhtml\">");                
        rootChildren.add(output);
 
        HtmlBody body = new HtmlBody();
        rootChildren.add(body);
 
        HtmlForm form = new HtmlForm();
        body.getChildren().add(form);
 
        ValueExpression messageProperty = expressionFactory.createValueExpression(elContext, "#{myBean.message}", String.class);
 
        HtmlOutputText message = new HtmlOutputText();
        message.setValueExpression("value", messageProperty);
        form.getChildren().add(message);
 
        MethodExpression helloMethod = expressionFactory.createMethodExpression(elContext, "#{myBean.action}", Void.class, new Class[0]);
 
        HtmlCommandButton hiCommand = new HtmlCommandButton();
        hiCommand.setActionExpression(helloMethod);
        hiCommand.setValue("Say hello");
        form.getChildren().add(hiCommand);
 
        MethodExpression navigateMethod = expressionFactory.createMethodExpression(elContext, "#{myBean.navigate}", String.class, new Class[0]);
 
        HtmlCommandButton navigateCommand = new HtmlCommandButton();
        navigateCommand.setActionExpression(navigateMethod);
        navigateCommand.setValue("Do navigation");
        form.getChildren().add(navigateCommand);
 
        output = new UIOutput();
        output.setValue("&lt;/html>");
        rootChildren.add(output);
    }    
}

This will be rendered as follows:

The code shows how components are created simply by using the new operator and a tree is created by just inserting the child components in the children collections of their parents. Action listeners are registered on action source components by setting a method expression that points to the scoped backing bean “myBean”, which is defined as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ManagedBean
public class MyBean {
 
    private String message;
 
    public void action() {
        message = "Hi!";
    }
 
    public String navigate() {
        return redirectOutcome(OtherPage.class);
    }
 
    public String getMessage() {
        return message;
    }    
}

Note that the bean features a navigation method that uses the class type of the target page to determine the navigation outcome.

By putting stuff in base classes or utility methods, page implementations can be simplified. For instance, the following shows the page where the user is navigated to after pushing the button on the first page. It inherits from a base class that already defines the html and outer body part, and only implements the body content:

1
2
3
4
5
6
7
8
9
public class OtherPage extends BodyTemplate {
 
    @Override
    public void buildBody(FacesContext context, HtmlBody body) {    
        HtmlOutputText output = new HtmlOutputText();
        output.setValue("This is a new page.");
        body.getChildren().add(output);        
    }
}

This page is rather simple and is rendered as:

As shown by the screen shots, if the project is called javavdl the initial page can be requested by requesting http://localhost/javavdl/intro.jsf, which is fully implemented using the Intro.java class given above. After clicking the navigate button, the user will be redirected to http://localhost/javavdl/test/otherPage.jsf, which is fully implemented by OtherPage.java. For this simple proof of concept, classes implementing pages have to reside in the package resources.javavdl.pages. Sub-packages in that package become paths relative to the deployment root of the application. E.g. /test/otherPage.jsf is implemented by resources.javavdl.pages.test.OtherPage.

The following is a picture of my workspace, showing that there is absolutely not a single xml file:

If this were used for real, the “src” package would probably be in a jar, and the application would consist of nothing more than this jar and the four classes shown in the demo package.

The current setup is really just a proof of concept. I personally think a declarative approach like Facelets is actually clearer, although some people actually do seem to like a purely programmatic approach to building a UI.

If people want to tinker with this, I’ve shared my Eclipse project where I implemented this here: http://code.google.com/p/javavdl (it currently depends on the Glassfish WTP server adapter being installed).

Arjan Tijms

Simple Java based JSF custom component

4 September 2011

Even though in JSF components have always been a central thing, actually creating them required a ridiculous amount of tedious work in JSF 1.x. Not only did you had to create the actual component, it also required you to:

  • Register the component in an XML file
  • Create a tag handler class, where you referenced the component by its registered name
  • Register the tag in .tld file.

You were also more or less supposed to create a separate renderer class, and although this actually has always been optionally, people seemed to interpret it as being a required part as well. Although none of this was really difficult, the sheer amount of work prevented everyone but component library builders from creating components.

JSF 2.0 addressed all of these concerns by introducing composite components, where you are able to create first-class components just by putting some existing components and/or markup in a Facelets file. For the majority of use cases where application builders needed their own customized components, this is actually all that’s needed.

For some cases however a Java based component is still a more natural fit. Although not as simple to create as composite components, creating Java based custom components has actually been simplified as well. Of the steps outlined above, only a registration for the tag is still required. The actual component can be rather simple:

components/CustomComponent.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@FacesComponent("components.CustomComponent")
public class CustomComponent extends UIComponentBase {
 
    @Override
    public String getFamily() {        
        return "my.custom.component";
    }
 
    @Override
    public void encodeBegin(FacesContext context) throws IOException {
 
        String value = (String) getAttributes().get("value");
 
        if (value != null) {        
            ResponseWriter writer = context.getResponseWriter();
            writer.write(value.toUpperCase());
        }
    }
}

Unfortunately, a registration in an XML file is still required to use this as a tag:

META-INF/my.taglib.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
    version="2.0">
 
    <namespace>http://example.com/test</namespace>
 
    <tag>
        <tag-name>customComponent</tag-name>
	<component>
            <component-type>components.CustomComponent</component-type>
        </component>
    </tag>
 
</facelet-taglib>

The custom component can now be used on a Facelet as follows:

page.xhtml

1
2
3
4
5
6
7
8
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:test="http://example.com/test"
>
    <h:body>   		
        <test:customComponent value="test"/>        
    </h:body>
</html>

As shown, creating a Java based JSF component that simply renders something is not that complicated. Although composite components should generally be preferred, Java based ones can come in handy and it’s an important extra tool.

It’s a shame perhaps the XML registration is still needed, but there’s a feature request in the JSF spec JIRA to make it largely unnecessary in a future JSF version. (if you care for this, please vote for it) Hopefully the actual Java code can also be further simplified if the family and component name would be defaulted in a future jSF version (the last e.g. to the fully qualified class name).


Arjan Tijms

Minimal 3-tier Java EE app, without any XML config

21 August 2011

Older versions of Java EE and Java frameworks in general were rather heavy with regard to required XML for configuration. Notorious were EJB2, Spring 2.x, JSF 1.x, Servlet 2.5 and many more.

These days things have improved quite a lot. In this post I’ll demonstrate a very simple, yet 3-tiered, Hello word application for Java EE. It uses JSF 2.1 and EJB 3.1 and absolutely not a single line of XML configuration.

The entire application consists of just 3 files: page.xhtml, BackingBean.java and BusinessBean.java. To run the application, create a dynamic web project called ‘mytest’ in Eclipse (EE edition) and delete everything that’s generated by default in WebContent. Copy page.xhtml to WebContent and copy both .java files to src. Add the app to your server (e.g. GlassFish 3.1) and browse to localhost:8080/mytest/page.jsf to see all the action.

The following shows the code of the 3 files involved:

page.xhtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
>    
    <h:body>
 
       #{backingBean.hello}
 
        <h:form>      
            <h:inputText value="#{backingBean.name}" />                    
            <h:commandButton value="Say Hello" action="#{backingBean.sayHello}" />
        </h:form>
 
    </h:body>
</html>

BackingBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
 
@ManagedBean
public class BackingBean {
 
    String name;
    String hello;
 
    @EJB
    BusinessBean businessBean;
 
    public void sayHello() {
        hello = businessBean.generateHello(name);
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getHello() {
        return hello;
    }
}

BusinessBean.java

1
2
3
4
5
6
7
8
9
import javax.ejb.Stateless;
 
@Stateless
public class BusinessBean {
 
    public String generateHello(String name) {
        return String.format("Hello, %s!", name);
    }    
}

The following shows that the project in Eclipse only has the 3 mentioned files:

The deployment itself also consists of only the 3 files mentioned (no IDE generated magic), although one extra step has been performed and that’s that the .java classes have been compiled to their .class versions and have been put into a newly generated directory WEB-INF/classes:

A simple exploded Java EE application deployment to GlassFish

Note the use of a couple of conventions that make this all work:

  • The context root is by default the name of the directory in which the app is deployed (technically: the exploded war name).
  • JSF by default maps the JSF controller servlet to *.jsf (and to /faces/* and *.faces).
  • Facelets files have a default suffix of .xhtml.
  • The backing bean’s default name in EL is the simple class name with the first letter de-capitalized.
  • The backing bean is by default in request scope.
  • The bi-directional binding from the view (page.xhtml) to the model via the EL expression #{backingBean.name} takes advantage of the JavaBean naming conventions for getters/setters.
  • The EJB is by default pooled and transactional.
  • A no-interface view is created for the EJB by default (since it doesn’t implement business interfaces).

Everything that is defaulted can be configured differently as needed. For instance, the default name in EL for the backing bean can be set to a different name via an attribute on the ManagedBean annotation, and the EJB can be made not transactional via an extra annotation. Some things would require XML to be configured differently. For instance, alternative mappings for the Faces Servlet or the default Facelets file suffix have to be configured in a web.xml file.

Finally, note that the goal of this example is to demonstrate one of the simplest possible setups and doesn’t necessarily adheres to all best practices. In reality, for non-trivial applications you’d want to declare you instance variables as private, definitely would not use the default package for your classes, probably create separate packages for your backing and business code, make sure *.xhtml is not directly accessible (e.g. by mapping the Faces Servlet directly to .xhtml in web.xml), and if your application really grows you might want to consider putting the business code in a separate module, add interfaces to the beans, etc etc.

But the point is that Java EE (and various other Java frameworks as well), now allow you to start with very simple defaults, making the barrier to enter much lower than before. You can then refactor and configure when the need arrises.


Arjan Tijms

Stateless vs Stateful JSF view parameters

3 July 2011

JSF defines the concept of view parameters, which are used to support URL parameters in GET requests (although it can be used for non-faces POST parameters as well).

View parameters are defined on a Facelet with the help of the f:viewParam tag. A typical usage looks like this:

<html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:h="http://java.sun.com/jsf/html"
     xmlns:f="http://java.sun.com/jsf/core"
 >
    <f:metadata>
        <f:viewParam name="foo_id" value="#{myBean.fooId}" />
    </f:metadata>

    <h:body>
        #{myBean.fooId}
    </h:body>
</html>

In this case myBean could look like this:

@ManagedBean
@ViewScoped
public class MyBean {
    private Long fooId;

    public Long getFooId() {
        return fooId;
    }

    public void setFooId(Long fooId) {
        this.fooId = fooId;
    }
}


There’s nothing really fancy going on here. When a GET request like localhost:8080/mypage?fooId=1 is processed, setFooId() is called, and when the page is rendered getFooId() is called. When we fire a GET request without the URL parameter, the setter will not be called. So, it looks like the presence of the URL parameter is what triggers the setter.

But what happens after we do a postback from that page? E.g. when we add the following to the Facelet:

<h:form>
    <h:commandButton value="do action" action="#{myBean.doAction"}"/>
</h:form>

and the following to the bean:

public void doAction() {
}

There will be no URL parameter present in the request after the postback, so it would seem logical the setter will not be called.

As it appears however, the setter will be called. What happens is that f:viewParam (UIViewParameter) is a stateful component. When it initially retrieves the URL parameter foo_id, it internally stores this in its view state. After the postback, the value is processed again and then also pushed into the model again (the backing bean). This is a direct consequence of the fact that in JSF a view is normally stateful and this behavior is actually consistent with how other UIInput components (like e.g. h:inputText) work. In case a backing bean is request scoped, this can also be really convenient as otherwise the initial URL parameter would be ‘lost’ after the first postback. See e.g. JSF 2.0: View parameters, where the author seems really happy with this behavior:

The UIViewParameter component also stores its value in the state, so that the value will also be available on the next postback request (most likely a clicked button or link). So you only need to provide your view parameter(s) once and not on every request.

Unfortunately, there are a couple of situations where a stateful f:viewParam can be a real nuisance. In the example given above the backing bean is already view scoped and takes care of managing its own state. Calling the setter again is simply redundant, but doesn’t hurt much. Even if the backing bean loads data from a DB based on this parameter, it probably does so in the preRenderView event handler with a guard that checks if the request is not a postback:

public void onPreRenderView() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        foo = fooDao.getByID(fooId);
    }
}

However, things get a little bit problematic when taking advantage of one of the killer features of view parameters: the ability to attach converters and validators to them. Instead of letting the backing bean load the Foo instance, we can use a universal converter for this and while at it validate right away that the foo_id is legal to be used by the current user (thus preventing parameter twiddling attacks). The code would then look like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
 >
    <f:metadata>
        <f:viewParam name="foo_id" label="foo_id" value="#{myBean.foo}" converter="fooConverter" validator="fooOwnerValidator"  />
    </f:metadata>

    <h:body>
        #{myBean.foo.id}

        <h:form>
            <h:commandButton value="do action" action="#{myBean.doAction"}"/>
        </h:form>
    </h:body>
</html>

and

@ManagedBean
@ViewScoped
public class MyBean {
    private Foo foo;

    public Foo getFoo() {
        return foo;
    }

    public void setFoo(Foo foo) {
        this.foo = foo;
    }

    public void doAction() {
    }
}

With f:viewParam being stateful, it will now do the conversion and validation on each and every postback. This is not only unnecessary (as the correct Foo instance is already safely kept in the view scoped MyBean), but it’s also a needless drain on system resources and a potential slow down for this view as it may involve a DB query for each and every postback.

So what we need for this particular usecase is an f:viewParam variant that doesn’t do this needless converting every time. There are a few options:

  1. Create a stateless version
  2. Only do conversion and model updates when value changes (suggested by my co-worker Bauke Scholtz)
  3. Also put converted value in state, always update model, reconvert when original changes

For this article I looked at the first option, as it seemed to be the easiest one to implement. The original UIViewParameter handles its state via the following methods (Mojarra 2.1.1):

@Override
public String getSubmittedValue() {
    return (String) getStateHelper().get(PropertyKeys.submittedValue);
}
public void setSubmittedValue(Object submittedValue) {
    getStateHelper().put(PropertyKeys.submittedValue, submittedValue);
}

In order to make a stateless variant, I simply inherited and provided alternative implementations for these two methods:

@FacesComponent("com.my.UIStatelessViewParameter")
public class UIStatelessViewParameter extends UIViewParameter {

    private String submittedValue;

    @Override
    public void setSubmittedValue(Object submittedValue) {
        this.submittedValue = (String)submittedValue;
    }

    @Override
    public String getSubmittedValue() {
        return submittedValue;
    }
}

I then created a new tag for this component in a facelet-taglib file (e.g. my-taglib.xml in META-INF in a jar):

<namespace>http://my.com/test</namespace>
<tag>
    <tag-name>viewParam</tag-name>
    <component>
        <component-type>com.my.UIStatelessViewParameter</component-type>
    </component>
</tag>

After this I can use this stateless variant on my Facelets:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:my="http://my.com/test"
 >
    <f:metadata>
        <my:viewParam name="foo_id" label="foo_id" value="#{myBean.foo}" converter="fooConverter" validator="fooOwnerValidator"  />
    </f:metadata>

    <h:body>
        #{myBean.foo.id}

        <h:form>
            <h:commandButton value="do action" action="#{myBean.doAction"}"/>
        </h:form>
    </h:body>
</html>

I can now do as many postbacks as I want, but the (expensive) conversion only happens once when the URL parameter is actually in the request. Exactly as we wanted!

There are two drawbacks though. The first is the fact that automatically generating a bookmarkable link that includes the original URL parameters via the includeViewParams attribute of e.g. h:link does not work anymore. The second is that if the required attribute has been set to true, then this will now complain the value is missing on a postback. This can be resolved by adding a #{!facesContext.postback} expression to this attribute, but this is not a very elegant solution.

To solve these drawbacks I’ll have to look into the method suggested by my co-worker Bauke and this might be the topic of a followup article.

Update:

A simple solution to avoid having to add the #{!facesContext.postback} at every place is to add the following method to the UIStatelessViewParameter class given above.

@Override
public boolean isRequired() {
    // The request parameter get lost on postbacks, however it's already present in the view scoped bean.
    // So we can safely skip the required validation on postbacks.
    return !FacesContext.getCurrentInstance().isPostback() && super.isRequired();
}

Thanks goes to Bauke for coming up with this ;)

Arjan Tijms

best counter