What’s new in JSF 2.2?

1 September 2012, by: Arjan Tijms

JSF 2.2 is final! The proposed final draft was posted on March 15, 2013 and the final vote was passed on April 17, 2013.

Originally it 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, and was first delayed to the first half of 2012 and then finally a date was set for the end of 2012, but that too proved to be insufficient. Following the delay of Java EE 7 itself, JSF 2.2 was then scheduled for 27/mar/2013.

So what made it into 2.2? The JSR gave an overview of ideas, but explicitly made the reservation that not all of those would be in the final spec. In May 2012, the sped lead Ed Burns identified the first 3 so-called ‘Big Ticket Features‘ for JSF 2.2:

  1. Faces Flows
  2. Multi-Templating Deferred to later release
  3. Sensible HTML5 support

During JavaOne 2012, 3 more features were designated as Big Tickets Features, and a JIRA list was created for them:

  1. Cross Site Request Forgery Protection
  2. Loading Facelets via ResourceHandler
  3. File Upload Component

Later the list was changed once again, and the proposed final list of Big Ticket Features became:

  1. Sensible HTML5 support
  2. Resource Library Contracts (a toned down Multi-Templating)
  3. Faces Flows
  4. Stateless views

As can be seen, the originally planned BIG-3 are mainly preserved (although Multi-Templating was severely reduced in scope), while the latter BIG-3 all had their “Big Ticket”-designation sacrificed in favor of Stateless views (implementation wise a minor last minute addition, but with a rather large impact).

One source worth looking at was 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’ve highlighted some items from that activity that I found interesting. The full list of all changes and the exact description of them can be found in the official JSF 2.2 specification.

Download

Latest 2.2 snapshot: implementation jar, source jar

Latest JSF 2.2 blog posts

The following in an excerpt of a list of blog posts from around the net about JSF 2.2 that I found interesting. The full list can be found on my ZEEF page.

New features

Cancelled

With the final release data of JSF 2.2 coming closer, a couple of features that were initially worked on where cancelled and removed for various reasons. Sometimes because a main stakeholder went off to do something else, sometimes because the end result wasn’t satisfactory and more times was needed, etc.

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.

A very simple example:

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

Further reading:

Commits for this feature have been done between 16/jun/11 and 31/jan/13.

Navigation


Faces Flow (spec issue 730) (mentioned in JSR) (Big Ticket Feature)

In web applications, and in applications in general actually, there is often the concept of a “flow” that takes the user through a series of screens. Such flows includes wizards, multi-screen subscriptions, bookings, etc.

Common for such flows is that they are not a random selection of pages linked to each other, but there is clear starting point and a goal where the user comes closer to after each successive step in the flow.

Implementing such flows has in the past been done with ad-hoc techniques, like simply linking full pages to each other and using the session scope to pass information between pages. The problem here is that this makes the result difficult to re-use and not safe when the user opens the same flow in more than one window.

For the last use case CDI already presented a solution via the conversation scope (@ConversationScoped), but this is just a part of the equation and by itself doesn’t enable truly reusable flows. Inspired by Spring Web Flow and ADF Task Flows , JSF 2.2 will directly add support for this concept using the name Faces Flow.

Faces Flow is a so-called Big Ticket Feature, which brings with it quite an amount of new concepts and terminology in JSF. This is explained in much more detail in the official proposal.

Part of this feature will be a new annotation, @FlowScoped, which in the draft implementation has the following JavaDoc:

FlowScoped is a CDI scope that causes the runtime to consider classes with this annotation to be in the scope of the specified flow. The implementation must provide an implementation of javax.enterprise.inject.spi.Extension that implements the semantics such that beans with this annotation are created when the user enters into the specified flow, and de-allocated when the user exits the specified flow.

(A remarkable detail is that JSF 2.2 thus introduces a dependency on CDI here, which might be indicative of JSF moving closer to CDI for other aspects as well)

A flow scoped bean is thus a bean that can be used to back a flow instead of just a single view (page). Unlike a session scoped bean it can only be accessed from views inside the flow (called ViewNodes), and like the view scope for a single view it exists for an instance of the flow, meaning two of the same flows in a different tab or window won’t interfere with each other. To realize this, Faces Flow heavily leans on the new Client Id feature (previously called Window Id).

A flow scoped bean looks as follows:

@Named
@FlowScoped(id = "someFlowName")
public class SomBean {
    public String someReturn() {
        return "/somePage.xhtml";
    }
}

The id someFlowName references the flow this bean will back, and which can be defined on an start node (aka the flow defining view) of a flow via JSF’s meta-data facility as follows:

/someFlowName/someFlowName.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:j="http://java.sun.com/jsf/flow"
>
    <f:metadata>
        <j:faces-flow-definition>
            <j:faces-flow-return id="someReturnName">
                <j:navigation-case>
                    <j:from-outcome>#{someBean.someReturn}</j:from-outcome>
                </j:navigation-case>
            </j:faces-flow-return>
        </j:faces-flow-definition>
    </f:metadata>
 
    <!-- Rest of view -->
</html>

(Notice the addition of a new taglib URI in core JSF: http://java.sun.com/jsf/flow)

By convention, creating a directory with the same name as the flow id and putting a view in it with again the same name (without the suffix), automatically designates it as the start node. (optionally, the id attribute of the j:faces-flow-definition element can be used if this structure can’t be met)

Via the j:initializer and j:finalizer sub-elements of the j:faces-flow-definition method expressions can be given that will be executed when the user enters respectively exits the flow, and thus function as a kind of constructor and destructor of a flow.

Intermediate nodes (aka member views) have to declare that they are part of the flow using the same j:faces-flow-definition element that we’ve seen in the start node, but via some at the moment of writing unknown convention (maybe again the name of the directory they reside in?) an id does not have to be explicitly specified. The following shows an example of an intermediate node:

/someFlowName/intermediateNode.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:j="http://java.sun.com/jsf/flow"
>
    <f:metadata>
        <j:faces-flow-definition/>
    </f:metadata>
 
    <!-- Rest of view -->
</html>

To enter and exit flows, JSF’s navigation system has been made aware of flows by allowing the flow- and exit ids to be used at all places where actions are allowed (this is a bit similar to how the Faces Views feature in OmniFaces has extended navigation to support extensionless URLs). To enter the above flow with id someFlowName we could use the following:

    <h:commandLink value="Enter flow" action="someFlowName" />

To exit from the flow we could use the following from any page that’s within the flow:

    <h:commandLink value="Exit flow" action="someReturnName" />

(remember that someReturnName was defined as the id of the j:faces-flow-return return element)

Following the established convention in Java EE that annotations (metadata in case of views) can be overridden by XML in deployment descriptors, everything that can be defined in the metadata section of the views can also alternatively be specified in faces-config.xml.

Besides an @FlowScoped bean, there’s also a new implicit EL variable introduced that’s associated with the current flow: facesFlowScope. This is a simple object-to-object map that can be used for storing arbitrary values. Being a map, input components can directly bind to it, e.g.:

    <h:inputText value="#{facesFlowScope.someKey}" />

The value stored here can be easily referenced on the same or another view of the flow, simply by referencing the expression, e.g.:

    The value that was submitted: <br/>
    #{facesFlowScope.someKey}

One important thing that really sets Faces Flows apart from ye olde navigation rules is that nodes in a graph do not only have to be views, but can be other things as well. The Javadoc on FlowHandler currently mentions the following:

  • View – A regular page like foo.xhtml in Facelets
  • Switch – One or more EL expressions of which the first that returns true determines the next node.
  • Return – Outcome to be returned to the caller of the flow
  • Method Call – An arbitrary method that just like a regular action method can return an outcome on which navigation can take place.
  • Faces Flow Call – A call to another flow, starting a nested flow (keeps the calling flow active until it returns)

The following shows an example utilizing a few more Faces Flow features:

    <f:metadata>
        <j:faces-flow-definition>
 
            <j:initializer>#{someBean.init}</j:initializer>
            <j:start-node>startNode</j:start-node>
 
            <j:switch id="startNode">
                <j:navigation-case>
                    <j:if>#{someBean.someCondition}</j:if>
                    <j:from-outcome>fooView</j:from-outcome>
                </j:navigation-case>
            </j:switch>
 
            <j:view id="barFlow">
                <j:vdl-document>barFlow.xhtml</j:vdl-document>
            </j:view>
            <j:view id="fooView">
                <j:vdl-document>create-customer.xhtml</j:vdl-document>
            </j:view>
 
            <j:faces-flow-return id="exit">
                <j:navigation-case>
                    <j:from-outcome>/exit</j:from-outcome>
                </j:navigation-case>
            </j:faces-flow-return>
            <j:faces-flow-return id="error">
                <j:navigation-case>
                    <j:from-outcome>/error</j:from-outcome>
                </j:navigation-case>
            </j:faces-flow-return>
 
            <j:finalizer>#{someBean.finish}</j:finalizer>
 
        </j:faces-flow-definition>
    </f:metadata>

Quite a few new methods have been added to the Java API, for instance javax.faces.application.Application has a new method FlowHandler getFlowHandler(). A FlowHandler can be used to obtain the current Flow, transition to a new point in the flow, get a reference to the map behind the facesFlowScope and even to dynamically add a complete new flow. Note though that it does not allow to dynamically manipulate existing flows, which are immutable after being created.

An instance of the Flow class is basically the run-time representation of the faces-flow-definition element, and can be used to obtain the initializer, finalizer, returns, switches, start node id and all view nodes that are part of the given flow. It can also be asked for the Id relative to the current client window. This currently consists of the Client Id and the Flow Id separated by an underscore.

At the time of writing, the implementation is very much a work in progress and various things are still changing on a day to day basis. According to the spec lead Ed Burns, “there will be big changes” in how the Faces Flow elements in the metadata section of a view can be used. The metadata way will most likely be completely removed and flows will be defined in an external file.

Commits for this feature have been done between 29/mar/12 and 07/jun/12.

HTML 5


Pass-through attributes (spec issue 1089) (Big Ticket Feature)

Among the many new features in HTML 5 are a series of new attributes for existing elements. Those attributes includes things like the type attribute for input elements, supporting values such as text, search, email, url, tel, range, number, date.

Additionally there are the so-called custom data attributes, also known as data-* attributes. These are attributes that don’t have a fixed name, but all start with data-, e.g. data-foo. Their purpose is to attach (small) amounts of data to HTML elements, which aren’t rendered but instead can be read by using JavaScript.

The problem is that existing JSF components don’t automatically support these new attributes and have to be updated in order to recognize them. This would be rather logical, if only those components really had to “support” them. But as a matter of fact, they actually don’t explicitly have to support them at all and just have to pass them through to the main rendered element (this is the only catch, for some components it might not be clear what that main element really is).

People have solved this problem in the past by using e.g. wrapped response renderers or custom HTML 5 render kits.

JSF 2.2 takes a universal approach to solve this problem and officially introduces the concept of pass-through attributes. These are a separate collection of attributes next to the existing attribute collection of a component. They are explicitly intended to be rendered directly to the client as opposed of being consumed/processed by the component itself.

From a Facelet, pass-through attributes can be set in 3 ways:

  1. Via a name-spaced attribute on the component tag
  2. Using the child TagHandler f:passThroughAttribute that sets a single attribute
  3. Using the child TagHandler f:passThroughAttributes that sets multiple attributes

Name-spaced attributes are an XML feature that wasn’t previously used by Facelets, but proves to be pretty convenient here to distinguish between two sets of tag attributes. The namespace for the pass-through attributes is http://java.sun.com/jsf/passthrough with the perhaps somewhat unfortunate default short name p (which is already commonly used by the popular PrimeFaces).

Using a name-spaced pass-through attribute looks as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://java.sun.com/jsf/passthrough"
>
    <h:form>
        <h:inputText value="#{bean.value}" p:placeholder="Enter text"/>
    </h:form>
 
</html>

Alternatively a TagHandler can be used as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
>
    <h:form>
        <h:inputText value="#{bean.value}" >
            <f:passThroughAttribute name="placeholder" value="Enter text" />
        </h:outputText>
    </h:form>
 
</html>

Note that this exactly mimics normal attributes vs f:attribute

Setting multiple attributes looks as follows:

<h:outputText value="Something" >
    <f:passThroughAttributes value="#{bean.manyAttributes}" />
</h:outputText>

Where #{bean.manyAttributes} refers to a Map<String, Object> where the values can be either literals or a value expression.

Using Expression Language 3 (part of Java EE 7, just like JSF 2.2), multiple attributes can also be directly defined using an EL expression:

<h:outputText value="Something" >
    <f:passThroughAttributes value="{"one":1, "two":2, "three":3}" />
</h:outputText>

One use-case for this last syntax variant would be when surrounding it by a c:if tag to conditionally set multiple attributes via a fairly terse syntax.

Attributes can also be set in Java via the new getPassThroughAttributes() and getPassThroughAttributes(boolean create) methods in UIComponent. Via the latter method one can test if there are any pass-through attributes without triggering any on-demand creation of data-structures, which is roughly equivalent to how HttpServlet#getSession(boolean create) works.

Setting a pass-through attribute from Java looks as follows:

UIComponent component = new SomeComponent();
Map passThrough = component.getPassThroughAttributes();
passThrough.put("placeholder", "Enter text");

As a bonus, to mimic f:passThroughAttributes a new f:attributes TagHandler was introduced as well, which with not surprisingly we can set multiple regular attributes via map.

Commits for this feature have been done between 22/jun/12 and 17/jul/12 and the associated issue has been marked as resolved.

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. The so-called XHR level 2 (aka XMLHttpRequest 2) does support this, but at the moment it’s still a working draft and only the very latest versions of the major browsers support it. Therefor it’s not yet a viable option to use in a specification.

There’s an iframe based trick available that works universally across browsers, but this by itself did not work directly with JSF prior to 2.2. To support this, changes had to be made to the mechanism that triggers a JSF request/response cycle. Interestingly, the reference implementation uses this as the transport mechanism and thus the AJAX upload in reality doesn’t use AJAX at all. The spec doesn’t mention this though and so leaves the door open for future implementations using XHR level 2.

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

Implementation of the AJAX file upload component was tracked separately as well.

The AJAX file upload component is in typical JSF fashion not a completely separate component, but just requires that the <f:ajax> tag is being added to the regular component:

  1. <h:form prependId="false" enctype="multipart/form-data">
  2.  
  3.     <!-- Now it's the AJAX file upload component -->
  4.     <h:inputFile id="fileUpload" value="#{someBean.file}" >
  5.         <f:ajax />
  6.     </h:inputFile>
  7.  
  8.     <h:commandButton value="Upload" />
  9. </h:form>

The type that’s produced by the upload component is the Servlet’s 3.0 javax.servlet.http.Part. As with regular input components, a validator can be attached which will then have access to the fully uploaded file.

Commits for the regular file upload have been done between 15/dec/11 and 26/sep/12 and the associated issue had been marked as resolved, while commits for the ajax part have been done on 26/Feb/13 and the associated issue had been marked as resolved as well.

Further reading:

Commits for the main feature have been done between 22/May/12 and 22/Feb/13.

State


Stateless views (spec issue 1055) Big Ticket Feature

When JSF 1.0 was released, people found it left a few things to be desired*. Over time nearly all of these initial issues have been taken care of (most of them in the JSF 2.0 release).

Yet, one fundamental issue that people have complained about since day one remained open; the issue of being stateful or put differently the lack of being stateless.

Now unlike the other issues, being stateful is not specifically a JSF issue. Many frameworks, especially component based frameworks are stateful (e.g. Wicket, ASP.NET, etc). The question is even if being stateful is actually an issue or simply something that follows from the fact that many applications do in fact have state and JSF is just managing that state for you.

In JSF 1.x the state mechanism was not entirely optimal though. It stored many things that were put as literals on the page defining a view. For instance, give a component an attribute foo=”bar” inside some table with 10 rows, and the string “bar” would end up 10 times in the view state. JSF 2.0 already fixed that with a mechanism called Partial State Saving, which made sure only changes to the state were saved. As a result of this, very little was still saved.

So why do people still want absolutely no state? There appear to be a number of different reasons, some justified, some debatable. Among those are the following:

  • Coolness, Hype and Hipness
  • Performance advantages
  • Memory advantages
  • Ability to route request to any node in cluster
  • Preventing view expired exceptions

The first item, “Coolness, Hype and Hipness”, is about the fact that being “stateless” is somewhat of a hype for some. According to them; in order to be cool, one has to be stateless, since stateless is what makes things cool (a kind of circle reasoning). The problem here is that many applications simply have state. Using a so-called stateless architecture doesn’t make that state magically disappear, and more often than not these applications have to dedicate some amount of code dedicated to sucking in state from a central DB at the start of each request and spitting it out to the same DB at the end of it. There are good reasons to go stateless (see below), but going stateless just because you’ve heard it’s the new trend and without taking your application requirements into account is not the best idea.

Performance advantages can be debatable as well. As it appears, JSF spends very little time in applying and saving state. This is especially true when state is saved on the server and no serialization is used. Being stateless can in fact have a negative effect if this state is actually really there and now has to be restored from some (remote) location.

Memory advantages can be equally debatable. The memory required by components to save their state is actually very small, while the state the user explicitly keeps (e.g. by using view scoped beans) is already under his or her control. If no state is wanted, the user can always opt to use request scoped beans exclusively.

The ability to route requests to any node in a cluster can be a serious one though. If state is required, no matter how small this state is, a postback HAS to go to the same node as where it originated from. This complicates load-balancing and makes it more difficult to remove a single node from the cluster for e.g. maintenance. Sticky sessions with buddy replication can somewhat solve this issue though, but it’s still not ideal.

Preventing view expired exceptions can also be serious. If e.g. a form is displayed on screen and state is saved on server, then upon the first postback JSF insists the state is there. But on the very first postback it’s nearly impossible to have any real state; namely the page was initially rendered in response to a repeatable GET request. So, whatever state there is saved can theoretically only be cached data that should be fully restorable. A workaround is to save state on the client in this case, but in JSF this is a global setting so then the entire application has to resort to this.

Although the issue asking for a stateless mode attracted the most votes ever, it was created relatively late and therefor wasn’t slot into the JSF 2.2 time frame. But then seemingly out of the blue Manfred Riem suddenly added a proprietary (RI-specific) feature to Mojarra that allowed for stateless views.

The implementation of this was surprisingly minimalistic, with the core of the change consisting of just two simple changes:

  • The TagHandler for <f:view> now processes the boolean attribute transient and passes it to UIViewRoot#setTransient
  • ViewDeclarationLanguage#restoreState simply does not restore state when UIViewRoot is stateless, but only builds the view

It simply makes use of the existing “transient” feature that had been available in JSF for some time on components (e.g. for use on a Form), but never got much attention. When this is set to true JSF would already skip such component when saving state. In fact, code could already set this attribute to true itself on UIViewRoot, but then ViewDeclarationLanguage#restoreState would complain. So, a slightly different explanation of the implementation of this feature is that JSF simply doesn’t complain anymore when there’s no state. And voila… just by removing some nagging JSF was suddenly stateless ;)

This Mojarra specific feature was subsequently proposed for standardization and retroactively taken as the implementation for spec issue 1055. As such a few additional changes were made that are discussed below.

The first additional change is that a public API method was added:

javax.faces.render.ResponseStateManager.isStateless(FacesContext context, String viewId)

This method only works for post backs though, and it thus shouldn’t be used to determine if the current view is stateless (UIViewRoot.isTransient can be used for that). Instead, it’s used to determine if the (non-)state that was last posted back is the special “stateless state”. To encode this “stateless state”, the RI uses the string “stateless” as the value for the view state parameter “javax.faces.ViewState”.

The second change is that if the product stage is “development”, a warning is now logged and a FacesMessage is added to the view when a stateless (transient) view root is used in combination with a view scoped bean.

Example of this feature:

<f:view xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    transient="true"
>
   <html>
        <h:head/>
        <h:body>
             <h:form>
                 <!-- Input components here -->
             </h:form>
        </h:body>
    </html>
</f:view>

The minimalistic approach of this feature does leave some room for improvement. With the current version stateless behavior has to be set per view and it’s orthogonal with the existing state saving options “client” and “server”. Setting an entire application to be stateless via the state saving method context parameter might be a next step. Datatables and similar components also still require that the model before and after a postback is exactly the same. With stateless views this is not necessarily the case, so an extended support for stateless components should use some kind of key here so the implementation can e.g. determine from which row an action originated.

As mentioned, a mere stateless view might not bring the huge performance benefits that are sometimes attributed to the concept “stateless”. However, closely associated (and perhaps expected?) with the concept is that of re-using views (pooling, singletons, …). This aspect is not addressed in JSF 2.2, but Leonardo Uribe is investigating this for MyFaces.

One practical thing to take specifically into account is that the “simply don’t save state” approach might not be compatible with existing components which may not expect that certain values are just not there. It’s left at the user’s discretion to verify that a given component indeed works in stateless mode.

For all its simplicity, a major result of this being put into the specification is that JSF 2.2 compatible components will have to take this into account; either fully support it in some way, or throw an exception of some kind. This awareness can be a great start for more advanced support.

*
For starters it lacked a native templating engine. JSP was (mis)used instead, but it was a bit of an abomination (e.g. life-cycle conflicts and things like the content-interweaving issue). GET support was also nothing to write home about. There was some rudimentary support, but not everybody was able to find this and the prevailing opinion was that JSF didn’t support it at all. For a component based framework, actually creating components was a rather tedious effort that involved the creation of many “moving parts”, which to make matters worse all had to be kept in sync whenever something changed (a situation that’s somewhat reminiscent to the early EJB2 beans).

Commits for this feature have been done between 07/Feb/13 and 28/Feb/13 and all associated issues have been marked as resolved

Resources


ResourceResolver unified with ResourceHandler (spec issue 809)

In JSF 2.0 and 2.1 there is the ResourceResolver and the ResourceHandler.

The ResourceResolver came in with JSF 2.0 from the once standalone Facelets 1.x. By default JSF loads Facelets views from the root of the WAR (the web application root), but via a custom ResourceResolver a user can provide other locations to load these views from. This can be any location for which a URL can be created, like another location and/or name in the WAR, a location inside some .jar file or even a database for e.g. views that are dynamically created at runtime.

The ResourceHandler is used to load artifacts that are served to the client. These artifacts can be anything but are typically things like CSS and JavaScript files. The ResourceHandler has a default location to load resources from as well (the not always entirely optimal world readable /resources in the web application root and META-INF/resources/ on the classpath) and like the ResourceResolver a user can provide a custom implementation that is able to load resources from other locations.

Owing to the different lineage the way to provide custom implementations for both these two artifacts is completely different.

For a custom ResourceResolver a context parameter in web.xml is needed. This is because it came in from a once external library and these can’t add their own tags to faces-config.xml but have to use the generic web.xml parameters:

<context-param>
    <param-name>javax.faces.FACELETS_RESOURCE_RESOLVER</param-name>
    <param-value>com.example.MyResourceResolver</param-value>
</context-param>

A custom ResourceHandler has to be registered in faces-config.xml as follows:

<application>
    <resource-handler>com.example.MyResourceHandler</resource-handler>
</application>

These different methods for registering isn’t really consistent and the names are not very clear either. Who would guess that a resource resolver is for custom Facelets, while a resource handler is for other resources?

An important issue with the separate ResourceResolver is that it’s defined specifically for Facelets. While Facelets is currently the default and only serious VDL (View Description Language) available, JSF is officially VDL neutral. This means there is no real way in JSF 2.1 to universally load VDL views for whatever VDL is being used. And even when programming specifically for Facelets, a ResourceResolver could not be consulted directly, but had to be obtained from the FaceletFactory, which itself could not be obtained in a standard way.

For JSF 2.2 the functionality of the ResourceResolver has been merged into the ResourceHandler, and the ResourceResolver itself has been deprecated. The main result of this merge is the following new method in ResourceResolver:

public ViewResource createViewResource(FacesContext context, String resourceName)

Compared to the venerable URL resolveUrl(String path) method that createViewResource replaces, the latter is specified to be applicable to general view resources and by default is functional equivalent to the existing createResource. Besides being much more consistent, this means it’s now also possible to load Facelets from a jar file without needing to provide a custom resolver.

Although not specified, it’s expected that JSF implementations will keep supporting ResourceResolver for a while, simply by letting the default resolver call the new createViewResource method. E.g.

public URL resolveUrl(String resourceName) {
    ViewResource viewResource = resourceHandler.createViewResource(context, resourceName);
 
    if (viewResource != null) {
        return viewResource.getURL();
    }
 
    return null;
}

In the reference implementation backwards compatibility is however only partially enabled.

When building a view a ResourceResolver is still consulted as in the following call chain:

ViewHandler#buildView ->  … -> ResourceResolver#resolveUrl -> ResourceHandler#createViewResource

But when checking if a view exists, a ResourceResolver is not consulted as in the following call chain:

ViewHandler#viewExists -> ResourceHandler#createViewResource

For the unification, the existing type javax.faces.application.Resource has been given a base class: javax.faces.application.ViewResource, consisting of only the URL getURL() method.

It’s interesting to note that this unification is attributed to both issue 719 and 809, however both issues originally asked for something else (more or less).

719 seems to ask for a way to load resources from a custom location, but was created before the ResourceResolver was brought into JSF and thus totally ignored this while it’s existence basically solved that issue.

809 is about a situation that existed in the short-lived 2.0, where in addition to a custom ResourceResolver it was also needed to provide a custom ExternalContext, which was very unclear. But this issue was already solved when JSF 2.1 introduced the ViewDeclarationLanguage#viewExists method.

Commits for this feature have been done between 07/Mar/12 and 05/Apr/12 and all associated issues have been marked as resolved


Resource Library Contracts (spec issue 763) Big Ticket Feature

Early on in the development cycle of JSF 2.2 there was excitement about a particular feature that was in the race for inclusion in JSF: multi-templating.

Multi-templating is the culmination of many different request (e.g. about “skinning”, or “re-useable app modules”) that all boil down to having the concept of “themes” in JSF. Theming is something that is supported by a lot of different systems. In operating systems one can change the appearance of e.g. Ubuntu using any of the build in themes, or using externally obtained ones. On the web, things likes WordPress or Blogger have elaborate support for it as well.

The overarching idea is that with the press of a button a user can change the appearance of an application in potentially many ways (colors, fonts, images, even layout) all at once while all functionality stays the same. From a programmer’s point of view the impact on the code should be absolutely minimal or even non-existent.

The multi-templating feature for JSF might have included a kind of admin management console, where users could download their own themes, switch between them on the fly, offer a marketplace, gallery or app store for theme bundles with meta-data where users of an application (not the programmers) could download themes and apply them to their account (assuming a kind of multi-tenancy setup), etc etc. There might have been some sort of inheritance in those app bundles, and who knows what.

Unfortunately this all proved to be too much and near the end of the JSF dev cycle (nov/2012) the feature was deferred to a later release.

Shortly after that a reduced scope was proposed and accepted for inclusion in JSF 2.2. Because the work on this started very late, the emphasis above all had to be on the reduced scope aspect, while keeping the door open for future more elaborate support.

The result is a relatively small but important addition to the existing resource handling mechanism; the introduction of a mere “prefix” for resource libraries that is more or less invisible to template clients. The “prefix” simply translates into a directory name that stores resources (which because of the “ResourceResolver unified with ResourceHandler” feature can also consist of Facelets views now, and thus Facelets templates). If the directory that stores those resources is in a .jar file, a “theme” can be changed by exchanging the .jar file at build time. There are two default locations for this: /contracts in the web application root, and META-INF/contracts on the class path.

Granted, it’s a far cry from what the initial multi-templating feature promised. There is no meta-data associated with a collection of resources, there’s no real interface and no real bundle. There has also been little focus on the run-time switching aspect (but there is some support, see below). Essentially it’s an extra directory used to group resources (a kind of namespace if you will), with a few mechanisms (some static, some dynamic) to determine which of those get imported into the “global namespace”.

Even though there’s no explicit interface present or any module-like declaration of what’s being exported, the spec refers to this directory as a contract and informally explains for the sake of discussion that the declaration of this contract can be thought to consists out of three elements:

  1. The templates present in the directory
  2. The insertion points in such templates
  3. Resources such as Images, CSS and JavaScript files present in the directory (optionally)

Following this, one could informally (e.g. in a readme.txt) declare a contract as follows:

The contract provides the template “foo.xhtml” which has insertion points “bar” and “kaz”.

Because of the informal declaration it’s thus not possible for tools to check if two different contract implementations (two different directories) indeed adhere to the same contract declaration (but remember the prevailing “reduced scope” argument for this feature and the possibility for this to be added in a later version of the spec).

There are basically three variations via which resource library contracts can be used:

  1. The Highlander rule: There can be only one
  2. Dynamic selection per view
  3. Static selection for view patterns

The Highlander rule; There can be only one, is akin to how injection is resolved in CDI. There simply has to be one implementation of a contract present in either contracts or META-INF/contracts. When this situation holds, no explicit configuration or qualification has to be done. The following demonstrates this:

Assume the following file structure:

/contracts
    /contract1
        template.xhtml
contract-client.xhtml

With the following file contents:

/contracts/contract1/template.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <h:body>
 
        Template from contract implementation 1 <br/>
 
        <ui:insert name="content"/>
 
    </h:body>
</html>

contract-client.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <ui:composition template="/template.xhtml">
 
        <ui:define name="content">
            Content from template client.	
        </ui:define>
 
    </ui:composition>
</html>

When packing these 2 files in a ROOT.war (yes only these 2 files, noting else is needed) and deploying it, requesting localhost:8080/contract-client.jsf will yield the following result:

Template from contract implementation 1 
Content from template client.

Notice that the Facelet “contract-client.xhtml” refers to just /template.xhtml as its template instead of /contracts/contract1/template.xhtml. Since /contracts/contract1/ is the only “contract directory” that contains a Facelet called template.xhtml the resolution is straightforward.

As mentioned above, we can change the template by deleting the /contracts/contract1/ directory and copying a new directory (possibly with a different name) there that contains a Facelet called template.xhtml. Of course that would not be a terribly exciting way to swap templates and certainly in JSF 2.1 we could also just delete a Facelet and copy a new one into whatever directory we used to store our templates. When we take into account that templates and resources can come from a single jar file as well, the “Highlander approach” can still be interesting as it allows us to change the look of the application at build time by exchanging a jar.

Things get more interesting when we consider the case where we have multiple implementations of the same contract present.

Assume the following file structure:

/contracts
    /contract1
        template.xhtml
    /contract2
        template.xhtml
contract-client.xhtml

With the same definitions as in the first example and the following new one:

/contracts/contract2/template.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <h:body>
 
        Template from contract implementation 2 <br/>
 
        <ui:insert name="content"/>
 
    </h:body>
</html>

There are now 2 conflicting definitions of template.xhtml. In CDI you will get an error if such ambiguity exists, but in JSF 2.2 it’s undefined behavior. The RI picks and chooses one at random. (perhaps an opportunity for a utility library or tooling to flag such error).

An individual view can dynamically (or when required statically) resolve this ambiguity by using the new contracts attribute on <f:view>. When we want contract-client.xhtml to statically use the version of its template in the /contract2 directory we could change it as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <f:view contracts="contract2">
        <ui:composition template="/template.xhtml">
 
            <ui:define name="content">
                Content from template client.	
        </ui:define>
 
        </ui:composition>
    </f:view>
</html>

The value of the contracts attribute can also come from an EL expression. With the help of an extra bean we can create a rudimentary theme switcher in JSF 2.2:

@Named
@SessionScoped
public class ThemeSwitcher implements Serializable {
 
    private static final long serialVersionUID = -1L;
 
    private String theme = "contract1";
 
    public void switchTheme() {
        if ("contract1".equals(theme)) {
            theme = "contract2";
        } else {
            theme = "contract1";
        }
    }
 
    public String getTheme() {
        return theme;
    }
}

contract-client.xhtml needs to be changed as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
>
    <f:view contracts="#{themeSwitcher.theme}">
        <ui:composition template="/template.xhtml">
 
            <ui:define name="content">
                Content from template client.
 
                <h:form>
                    <h:commandButton action="#{themeSwitcher.switchTheme}" value="Switch theme" />
                </h:form>	
            </ui:define>
 
        </ui:composition>
  </f:view>
</html>

Note that the contracts attribute is now bound to the EL expression #{themeSwitcher.theme}.

Unfortunately, the contracts attribute in only allowed to be used on a top-level <f:view>. This means we can’t e.g. use a ‘normal’ template to abstract it away. If we want to switch the theme of an entire application this way we need to put this expression on each and every view, which is not entirely DRY.

Finally there is the “Static selection for view patterns” options. With this we can configure an entire application or a collection of views (via a pattern) to use a specific contract. This is however a static configuration and thus can’t be used for any run-time switching of themes.

Static selection for view patterns can be done via the new <resource-library-contracts> element in faces-config.xml. If we remove the <f:view> from contract-client.xhtml again and then leave the rest as is, we can select that the template to be used is from the contract1 directory with the following JSF 2.2 faces-config.xml file in WEB-INF:

<?xml version="1.0" encoding="UTF-8"?>
 
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
	version="2.2">
 
	<application>
		<resource-library-contracts>
			<contract-mapping>
				<url-pattern>*</url-pattern>
				<contracts>contract1</contracts>
			</contract-mapping>
		</resource-library-contracts>
	</application>
 
</faces-config>

(note that for JSF 2.2 the well known java.sun.com name-space changed to xmlns.jcp.org)

It would have been great if the <contracts> element could have accepted an EL expression, but this is not possible and only literals are allowed. It’s fairly easy to change the value of <contracts> to contract2, but it requires a restart and it will take effect for all users of a web app.

While this feature may leave some things to be desired, it’s nevertheless an excellent foundation to build more elaborate functionality. Hopefully JSF 2.3 will indeed focus on this.

Further reading:

Commits for this feature have been done between 15/Nov/12 and 16/Mar/13 and all associated issues have been marked as resolved.

Injection / Annotations


Injection in most 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 is possible in many more artifacts, like for instance in a StataManager, a ResourceHandler, and even in a PartialViewContectFactory. Specifically injection into an ActionListener, SystemEventListener and PhaseListener can be really useful and is now possible.

The full list of artifacts that are injection candidates is as follows:

  • javax.el.ELResolver
  • javax.faces.application.ApplicationFactory
  • javax.faces.application.NavigationHandler
  • javax.faces.application.ResourceHandler
  • javax.faces.application.StateManager
  • javax.faces.component.visit.VisitContextFactory
  • javax.faces.context.ExceptionHandlerFactory
  • javax.faces.context.ExternalContextFactory
  • javax.faces.context.FacesContextFactory
  • javax.faces.context.PartialViewContextFactory
  • javax.faces.event.ActionListener
  • javax.faces.event.SystemEventListener
  • javax.faces.lifecycle.ClientWindowFactory
  • javax.faces.lifecycle.LifecycleFactory
  • javax.faces.lifecycle.PhaseListener
  • javax.faces.render.RenderKitFactory
  • javax.faces.view.ViewDeclarationFactory
  • javax.faces.view.facelets.FaceletCacheFactory
  • javax.faces.view.facelets.FaceletFactory
  • javax.faces.view.facelets.TagHandlerDelegateFactory

Unfortunately the ones that perhaps matter most of all, converters & validators, are still not injection targets. It’s likely that those will be taken into consideration for JSF 2.3 though.

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.


CDI compatible @ViewScoped (spec issue 1087)

One of the many important features that JSF 2.0 brought was the view scope. This is the scope that is active for a single view (page) and post-backs to that view from a single window or tab. Managed beans utilize this scope mainly via the @ViewScoped annotation (there’s an XML variant for the masochists among us).

Despite all the goodness that @ViewScoped brought us, it’s unfortunately* also known as the one thing that prevented CDI to be a drop-in replacement for ye olde JSF Managed Beans. Namely, @ViewScoped works exclusively with those JSF Managed Beans. This poses a dilemma. For many problems the view scope is the better scope, but CDI beans are the better bean (always). Choosing @ViewScoped means giving up CDI, and choosing CDI means giving up @ViewScoped.

(* This unfortunate situation is a result from the fact that CDI finished relatively late in the Java EE 6 development cycle, while JSF 2 finished rather early. The annotation based managed beans facility in JSF 2 may look like a duplication of the CDI efforts, but it’s actually the exact same facility that was in JSF 1.0, only with annotations as alternative for XML.)

Several third parties like Seam 3 and CODI have provided solutions for this problem, but supposedly many of them have various issues, and at any length such important core functionality should maybe not depend on a third party.

So, JSF 2.2 will support the view scope directly for CDI, by providing a CDI extension for this.

Besides this plain fact, there are a couple of interesting observations to be made.

The first is that JSF gives a very clear signal it’s moving towards CDI. It now has a second dependency on CDI, although an optional one. If CDI is not available the annotation will simply not have any effect.

The second is that JSF 2.2 has introduced a new annotation, javax.faces.view.ViewScoped instead of reusing the existing javax.faces.bean.ViewScoped as most if not all existing third party solutions do. The reason for this is that this way the entire javax.faces.bean package can be deprecated later on. Indeed, javax.faces.bean.ViewScoped has gotten a “pre-deprecate” warning in its Javadoc:

The annotations in this package may be deprecated in a future version of this specification because they duplicate functionality provided by other specifications included in Java EE. When possible, the corresponding annotations from the appropriate Java EE specification should be used in preference to these annotations. In this case, the corresponding annotation is javax.faces.view.ViewScoped. The functionality of this corresponding annotation is identical to this one, but it is implemented as a CDI custom scope.

Early versions of the new annotation hinted that GET requests back to the same view would also be considered to be within the same view scope. With the current annotation this is not the case, as a GET request will always create a new view instance. However in later iterations this mysterious comment disappeared again.

The exact Javadoc that said this was:

When this annotation, along with javax.inject.Named is found on a class, the runtime must place the bean in a CDI scope that remains active as long as the user remains on the same view, including reloads or navigations from the current view immediately, with no intervening views, back to the same view, even via an HTTP GET request.

(emphasis mine)

But as said, this comment was removed, so most likely the new CDI view scope will NOT magically work for GET requests as well.

Example in code:

import javax.inject.Named;
import javax.faces.view.ViewScoped;
 
@Named
@ViewScoped
public class Foo {
    // ...
}

Commits for this feature have been done on 31/aug/12 and the associated issue has been marked as resolved, but the actual implementation had been deferred to JAVASERVERFACES-2506 for which a commit was done on 28/sep/12 and has been marked as resolved. Several renames and strengthening of the implementation was done via a diverse range of other issues, e.g. JAVASERVERFACES-2641, for which commits have been done between 9/jan/13 and 10/jan/13 and which has been marked as resolved as well.


Facelets Component Tag can be declared via annotation (spec issue 594)(mentioned in JSR)

Before JSF 2.0, creating (java based) custom components was a lot of work. The amount of required work was largely reduced in JSF 2.0, mainly because Facelets does not require an explicit tag handler and because a component can be registered via its annotation.

However, one tedious requirement remained. In order to make a component useable in Facelets, a tag name for it had to be declared in a *-taglib.xml file.

In JSF 2.2 this requirement has been lifted and the tag declaration can be done via the component’s annotation. For this the @FacesComponent annotation introduces 3 new attributes:

  • createTag – If set to true the component will be directly useable via a tag on a Facelet.
  • tagName – Optional explicit name for the tag. If omitted, the class’ simple name with the first character in lowercase will be used.
  • namespace – Optional explicit namespace for the tag. If omitted the namespace ‘http://xmlns.jcp.org/jsf/component’ will be used.

For instance:

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

Without the need to configure or declare anything else, this component can now be used on a JSF 2.2 Facelet as follows:

page.xhtml

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

Commits for this feature have been done between 13/feb/12 and 15/feb/12 and the associated issue has been marked as resolved.


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.


Component and validator annotations default to simple class name (spec issue 703)

With Java EE 5 a trend was started to introduce convention over configuration into the platform, a trend which continued strongly in Java EE 6.

For annotations that cause a class to be registered under some name this typically means the simple class name (class name without the package) with the first letter de-capitalized is taken as the default for this name. For instance, in JSF 2 with the following class definition the managed bean will be available to EL using the name foo

@ManagedBean
public class Foo {
    // ...
}

If needed the name can be specified explicitly:

@ManagedBean(name="myfoo")
public class Foo {
    // ...
}

For components and validators this convention wasn’t used, and the name always had to be specified fully, e.g. for a component:

@FacesComponent("bar")
public class Bar extends UIComponentBase {
    // ...
}

Notice the inconsistency between “name=” for the managed bean and not having to use an attribute name for the component.

In JSF 2.2 the name can now be omitted for components, converters and validators as well, so the code shown above can become:

@FacesComponent
public class Bar extends UIComponentBase {
    // ...
}

This makes the overall platform a bit more consistent and is especially useful for simple implementations in application space. Most likely component libraries will still provide a (long) explicit name to prevent name clashes.

Commits for this feature have been done on 07/mar/12 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


Programmatic configuration (spec issue 533)

In Java EE, configuration can generally be done via either annotations or XML. Increasingly, there’s also a third variant available: programmatic configuration. A well known example of this is Servlet 3.0, where a Servlet can be added via the @WebServlet annotation, the <servlet> element in web.xml, or by calling ServletContext#addServlet.

This is supported in JSF as well, e.g. via the Application and FactoryFinder classes. The OmniFaces utility library for example uses this to programmatically set a new ViewHandler.

Those existing classes however are not always optimal. They are more or less at a kind of intermediate level: they accept objects (as opposed to Strings), but in a rather raw form. In order to satisfy the API, the user still has to do some work manually and in addition to that often has to make the calls at exactly the right time. Too early and the call fails because nothing related to JSF has been initialized yet, too late and the call won’t have any effect since the artifact in question has already been set and doesn’t allow the programmer to programmatically reset it. Furthermore, just like in Servlet 3.0, they cover only a fraction of the functionality that annotations and XML cover.

JSF 2.2 will introduce an exciting new variant of programmatic configuration: a user specified callback method in which a DOM root representing the system’s meta-data (faces-config.xml) can be populated right before JSF processes it. In a way this is at a lower level than the existing programmatic configuration, since it will only allow String based values. On the other hand, it’s at a higher level since the programmer only has to specify the FQN of e.g. a ViewHandler class and does not need to worry about calling its constructor with the previous ViewHandler (if any) and making sure all injections have been done and life-cycle methods have been called for it.

A difference with other programmatic methods is that this particular API only allows for new configuration to be contributed, i.e. it can not be used to modify or append directly to existing configuration. It should be treated just like having an additional faces-config.xml file present in the application.

Being a callback, it does automatically solves the problem of when it’s the right time to call the configuration API.

Said callback method is provided by a class that extends and implements the abstract class javax.faces.application.ApplicationConfigurationPopulator. A file containing the name of the implementing class has to be put into the META-INF/services directory with as name the fully qualified class name of this abstract class. JSF can then use the java.util.ServiceLoader mechanism to pick this class up. Incidentally this is the same mechanism that ServletContainerInitializer uses.

User code can get a hold of all such service instances (one per jar that’s on the classpath) as well using code such as the following:

ServiceLoader services = 
    ServiceLoader.load(ApplicationConfigurationResourceDocumentPopulator.class);

The method to be implemented is called populateApplicationConfigurationResource, returns void and accepts a single argument of type org.w3c.dom.Document.

E.g.

META-INF/services/javax.faces.application.ApplicationConfigurationPopulator

com.example.MyInitializer

 

com/example/MyInitializer.java

public class MyInitializer extends ApplicationConfigurationPopulator {
 
    public void populateApplicationConfiguration(Document document) {
        String ns = document.getDocumentElement().getNamespaceURI();
 
        Element applicationEl = document.createElementNS(ns, "application");
        Element viewHandlerEl = document.createElementNS(ns, "view-handler");
 
        viewHandlerEl.appendChild(
            document.createTextNode(MyViewHandler.class.name())
        );
 
        applicationEl.appendChild(viewHandlerEl);
        document.appendChild(applicationEl);
    }
}

(The DOM API is rather verbose, but with a small utility method this can easily be reduced to something like addNode(document, “application/view-handler”, MyViewHandler.class);)

Commits for this feature have been done between 30/may/12 and 12/sep/12 and the associated issue has been marked as resolved.


FlashFactory and FlashWrapper (spec issue 1071)

Next to the FaceletFactory, another new factory obtainable via the FactoryFinder in JSF 2.2 is the new FlashFactory. This factory can be used to create Flash instances.

Obtaining those instances was already possible before JSF 2.2 via ExternalContext#getFlash and this will remain the default way for ‘normal’ user code. The fact that there’s now a standard factory underneath means that there’s a hook available for overriding and/or wrapping the default implementation. This mechanism is explained here.

The factory is obtainable via the constant FactoryFinder.FLASH_FACTORY (javax.faces.context.FlashFactory).

Overriding it in faces-config.xml can be done as follows:

  1. <factory>
  2.     <flash-factory>com.example.MyFlashFactory</flash-factory>
  3. </factory>

In addition to a factory, a new convenience wrapper class for the Flash, FlashWrapper has been added. Similar to existing wrapper classes like ViewHandlerWrapper, ExceptionHandlerWrapper, etc this allows one to wrap an existing Flash instance and selectively override methods.

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


Instantiating (composite) component in Java via tag name (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 now provides an explicit API for this, which as a side-effect can also be used to instantiate regular components by their namespace/tag name. The following shows an example:

Creating a regular standard component, without any attributes set to pre-set values:

FacesContext context = FacesContext.getCurrentInstance();
ViewDeclarationLanguage vdl = context.getApplication()
                                     .getViewHandler()
                                     .getViewDeclarationLanguage(context, context.getViewRoot().getViewId());
 
UIOutput outputText = (UIOutput) vdl.createComponent(
                                        context, 
                                        "http://java.sun.com/jsf/html",
                                        "outputText", null
                                  );

Given an app with a /resources/myComposites folder in the web root containing a composite component myComponent.xhtml, we can create it programmatically as follows:

FacesContext context = FacesContext.getCurrentInstance();
ViewDeclarationLanguage vdl = context.getApplication()
                                     .getViewHandler()
                                     .getViewDeclarationLanguage(context, context.getViewRoot().getViewId());
 
UINamingContainer namingContainer = (UINamingContainer) vdl.createComponent(
                                        context, 
                                        "http://java.sun.com/jsf/composite/myComposites",
                                        "myComponent", null
                                  );

Commits for this feature have been done between 02/oct/11 and 01/feb/13 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.


Many additional wrapper classes

In JSF many parts of the framework can be replaced by user supplied versions. Those versions can either completely replace the existing functionality, or can do this partially. For this the decorator pattern is utilized, where the user supplied implementation gets a reference to the existing implementation and can delegate functionality that it doesn’t want to replace to that.

To make this easy, JSF offers a bunch of wrapper classes; ViewHandlerWrapper for ViewHandler, StateManagerWrapper for StateManager, etc.

Until now there weren’t wrapper classes for:

  • Lifecycle
  • ActionListener
  • Renderer
  • NavigationCase
  • NavigationHandler

In JSF 2.2 there now are, with the predictable names:

  • LifecycleWrapper
  • ActionListenerWrapper
  • RendererWrapper
  • NavigationCaseWrapper
  • NavigationHandlerWrapper

For LifecycleWrapper there wasn’t a separate JIRA issue, but it was committed as part for the work for spec issue 949, while many others had their own issue, e.g. ActionListenerWrapper had spec issue 993.

Commits for this feature have been done between 09/May/11 and 30/Nov/12 and all associated issues have been closed.

Lifecycle


Identify client windows via a Window Id (spec issue 949)

Arguably one of the biggest problems that has been plaguing web application development since its inception is the inability to distinguish requests originating from different windows of a single browser. Not only has an actual solution been long overdue, it has taken a long time to realize this even was a problem.

The root of the problem, as always, is that the HTTP protocol is inherently stateless while applications in general are not. There is the concept of a cookie though, which is overwhelmingly the mechanism used to distinguish requests from different users and to implement things like a session scope where on its turn the bulk of login mechanisms are based on.

While a cookie does work for this, it’s global per browser and domain. If a user opens multiple tabs or windows for the same domain then requests from those will all send the same cookie to the server. Logging in as a different user in a different window for the same website is thus not normally possible, and having workflows (involving post-backs, navigation) in different windows can also be troublesome because of this.

In JSF there are various solutions that are somehow related to this. The view scope effectively implements a session per window as long as the user stays on the same page and does only post-backs. The Flash is used for transferring data between different pages (presumably within the same window) when navigation is done via Redirect/GET. There’s a wide variety of scopes implemented by third parties that do something similar.

All of these have some implicit notion or assumption of the concept of a ‘client window’, but there is no explicit API for this.

JSF 2.2 will introduce support for two different aspects of this:

  1. Identification of an individual window: the Client Window Id
  2. API and life-cyle awareness of the window concept

The first item unfortunately cannot be implemented perfectly, as ultimately only the HTTP protocol can do this. HTTP/2.0 might indeed do this, but it will be some time before that will be available. JSF will do a best-effort though and might allow users to easily plug-in their own implementation if they so desire.

Since no method to identify a window is perfect, the user can configure the preferred method in web.xml via a context parameter:

<context-param>
    <param-name>javax.faces.CLIENT_WINDOW_MODE</param-name>
    <param-value>url</param-value> 
</context-param>

The spec only demands support for url and none. none is the default and means the feature is disabled.

The only other choice url means the feature is enabled, and that the client window is tracked via either a hidden field or a request parameter.

The hidden field should be written during state saving with the name “javax.faces.ClientWindow” that contains the client window ID. Just like the view ID, JSF can use this after a post-back. For GET requests the spec defines the jfwid query parameter, which has to be added to links and contains the same client window Id value (the Servlet spec describes a similar mechanism for the session ID). E.g.

http://example.com/foo?jfwid=953FAAGhGhYF78%3A1

When both the hidden field and query parameter are present, the hidden field takes precedence.

It’s an open question what should happen when such link is opened in a new window or tab (e.g. using a browser’s “Open in New Tab” feature when right clicking on a link).

If needed, a page author can disable the appending of the jfwid parameter to a link when using the core components <h:link> and <h:button> via the newly introduced attribute disableClientWindow. E.g.

<h:link value="New" outcome="aview" disableClientWindow="true" target="_blank" />

Component authors can offer support for this as well using the disableClientWindowRenderMode method on the ClientWindow class. E.g.

FacesContext context = ...
 
ClientWindow clientWindow = context.getExternalContext().getClientWindow();
if (clientWindow != null) {
    try {
        clientWindow.disableClientWindowRenderMode(context);
        // Do stuff
    } finally {
        clientWindow.enableClientWindowRenderMode(context);
    }
}

Modes other than url and none are possible, but are for now implementation specific. Non-recognized modes seem to be allowed to be silently interpreted as url. Remarkable is that the RI never actually checks for the value url anywhere.

In the reference implementation the client window ID consists of the session ID (JSESSIONID) followed by separator and a sequential number, e.g. 953FAAGhGhYF78:1. The exact format of this ID is implementation specific and no assumptions can be made that it contains the session ID.

There are various places where the client window concept will appear in the API, but most visible will be the new class that was already briefly mentioned above: ClientWindow and the method to obtain it: ExternalContext#getClientWindow().

The JavaDoc for ClientWindow mentions the following:

The lifetime of a ClientWindow starts on the first request made by a particular client window (or tab, or pop-up, etc) to the JSF runtime and persists as long as that window remains open or the session expires, whichever comes first. A client window is always associated with exactly one UIViewRoot instance at a time, but may display many different UIViewRoots during its lifetime.

Note that client window ID nor ClientWindow implement a new scope, but are instead a basis on which existing and new scopes can be portably implemented.

See also these resources:

Commits for this feature have been done between 23/feb/12 and 23/oct/12 and the associated issue has been marked as resolved, but extra commits were done between that date and 14/mar/13. A separate issue to implement this feature was created at JAVASERVERFACES-2572. A commit for the implementation issue has been done on 02/Nov/12 and the associated issue has been marked as resolved.


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

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


All component types in metadata activate full lifecycle (spec issue 762)

JSF 2.0 added the concept of a metadata section in a view. This special section has two properties; its content can be read without constructing the entire view, and on a non-postback (non-faces, e.g. an initial GET request) components residing in this section can do something before the view is being rendered. Before JSF 2.0 this was not possible; on an initial GET request to a view only the lifecycle phase RENDER_RESPONSE was executed.

There was however one thorny issue, and that’s that the spec asked for checking for the presence of UIViewParameters (<f:viewParam>) as a precondition for executing lifecycle phases before RENDER_RESPONSE. In practice this meant a dummy <f:viewParam> had to be added in order for other kind of components to do anything before the view is rendered.

In JSF 2.2 such dummy isn’t needed anymore and there’s simply a check for a metadata section with components inside it.

To support this a new method has been added to javax.faces.view.ViewMetadata:

public static boolean hasMetadata(UIViewRoot root)

This will return true if there’s metadata for the given view, and false otherwise.

Commits for this feature have been done between 08/jun/11 and 31/jan/13 the associated issue has been marked as resolved.


Input fields can be updated with AJAX after validation error (spec issue 1129)

A particular nasty issue in JSF 2.0 (and before) is that it’s not possible to update any input fields with AJAX after a validation error has occurred.

Consider the following use case:

There’s a form on screen with an input field for name. Users can either type in the name directly, or press a button and choose a name from a dialog. After the user makes a selection in the dialog, the input field for name is updated with that value via AJAX.

So far so good.

But, if the user types in a name directly and a validation error happens because of that, the dialog is suddenly unable to put a new (valid) value in the input field.

This is because of a rule in JSF that input components (EditableValueHolders) are not allowed to pull new values in from the model to which they are bound after a validation error has occurred. The only way to put a new value into them is by requiring the user to manually enter something. This is however totally unintuitive and breaks many use cases.

The issue has been known for some time as has been documented as early as 2007. Users provided various cleaning solutions in forums. The issue also frequently came up on stackoverflow.

In response to this, libraries such as OmniFaces implemented a reusable solution for this problem. When a little later PrimeFaces also implemented a solution, it became clear something standardized was needed.

Çağatay Çivici, the lead developer of PrimeFaces (who is also a JSF EG member), therefor contributed the specification of a standard way to reset those input fields.

The primary result of this specification for page authors is the addition of a new attribute to the <f:ajax> tag; resetValue. Setting this to true will reset all components that are to be re-rendered, e.g. the components of which the id is given in the render attribute. Note that the official VDL doc says:

This will cause resetValue() to be called on any EditableValueHolder instances encountered as a result of this ajax transaction.

Intuitively this may not be entirely clear, as another set of instances that are involved with the AJAX transaction are those that are specified in the execute attribute. But in this case “instances encountered as a result…” thus means those specified in the render attribute, or from the server’s point of view the IDs returned by javax.faces.context.PartialViewContext.getRenderIds().

Example:

<h:commandButton value="DoStuff" action="#{someBean.someAction}">
    <f:ajax render="field1 field2" resetValues="true" />
</h:commandButton>

Then there’s also a mechanism for use with non-AJAX request; <f:resetValues>. This is a tag handler that can be nested inside “action components” (javax.faces.component.ActionSource instances), and that installs an ActionListener on its parent component that resets all components that are given in its render attribute. In effect it’s thus a kind of specialized action listener tag.

Example:

<h:commandButton value="DoMoreStuff">
    <f:resetValues render="field1 field2" />
</h:commandButton>

This may look odd at first since the entire purpose of resetting components was to update them via AJAX, and this resets after a non-AJAX request. However, it means that by using this “action listener” components are never in the non-updatable state to begin with, which may be preferable in some situations. Care should be taken that the render attribute DOES NOT accept the typical ‘macros’ like @form and @all.

As for the Java API, JSF 2.0 did already add the resetValue convenience method to EditableValueHolder, but has now also added a public convenience method to reset all components from a given collections of Ids in the entire tree:

javax.faces.component.UIViewRoot.resetValues(FacesContext, Collection<String>)

This method mirrors exactly what <f:ajax resetValues=”true” /> and <f:resetValues> do.

Further reading:

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

    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.


    Standardized server state serialization (spec issue 1127)

    Every time a view is rendered in JSF that uses state, this state is stored somewhere. In case state is stored on the client all objects and their primitives that make up this state are serialized and as an (encrypted) base64 encoded string sent to the client. In case state is stored on the server only a view state Id is sent to the client.

    This view state Id points to a capture of the state stored in server memory. Making this “capture” can be done by just storing pointers (a shallow copy), or by doing the same as is done for the state on the client and serializing everything (making a deep copy).

    Both these methods have their advantages and disadvantages. A shallow copy is much cheaper in terms of both CPU and memory utilization and allows you to inject EJB beans in @ViewScoped beans, but if fields of an object are changed in one ‘copy’, they change in all other copies. This last effect could lead to unexpected results. Serialization on its turn requires much more CPU and memory and doesn’t work with EJB injection (of which the proxies aren’t serializable), but it does allow for a true history of state.

    The two major (and practically only) JSF implementations Mojarra and Myfaces both offered proprietary context parameters to set the desired behavior: com.sun.faces.serializeServerState for Mojarra and org.apache.myfaces.SERIALIZE_STATE_IN_SESSION for MyFaces. A major problem that portable applications are facing in JSF 2.1 and before is that Mojarra and MyFaces have their defaults reversed. Mojarra defaults to not serializing, while Myfaces defaults to serializing.

    In JSF 2.2 this proprietary context parameter will be standardized via the new javax.faces.SERIALIZE_SERVER_STATE. However, JSF 2.2 still does not mandate what the default should be, but does state that serializing for state on server is optional, carefully hinting at not serializing being a good default. Mojarra at least will continue to have not serializing as the default.

    Example of setting server state to use serialization:

    <context-param>
        <param-name>javax.faces.SERIALIZE_SERVER_STATE</param-name>
        <param-value>true</param-value>
    </context-param>

    Commits for this feature have been done on 22/aug/12.


    Configurable resource directory (spec issue 996)

    In JSF 2.0 a special directory was introduced called the “resources directory”. This directory is a directory called resources in the root of a web archive and is to load the definition of composite components by convention. Aligning with the entire easy-of-use and no-configuration theme, there is nothing that needs to be configured for this. A developer can create a sub-directory in this resources directory which will become a namespace, and all elements in this sub-directory will be automatically recognized as composite components.

    This entire mechanism is by itself a great example of the ease of use improvements that JSF 2.0 brought. In the older thinking, a developer would have to put an XML file somewhere, then register the XML file itself, then register in this XML file what the namespace was and where the definitions of component could be found. Not difficult, but rather tedious indeed.

    So the concept of this auto-registering resources directory was a great step forward. Unfortunately, there is one small problem. The resources directory is an ordinary directory in the web root, meaning its world readable by default. This on its turn means the source code of composite components is world-readable if there’s no .xhtml to .xhtml mapping, or an attempt can be made to execute them directly as-if they were top-level pages. Both effects are undesirable as any source level artifact should be totally inaccessible to random clients.

    JSF 2.2 will therefor introduce a context parameter called javax.faces.WEBAPP_RESOURCES_DIRECTORY that will allow a developer to choose a different directory. At best this is a compromise, since the defaults are still unsafe and these defaults are what the majority of developers will (initially) use. For new JSF applications, this will thus be more or less a required configuration parameter, which sadly goes against the no-config theme that brought us the resources directory in the first place.

    Example of setting the resources directory to a non-world-readable directory:

    <context-param>
        <param-name>javax.faces.WEBAPP_RESOURCES_DIRECTORY</param-name>
        <param-value>WEB-INF/resources</param-value>
    </context-param>

    Further reading:

  • Commits for this feature have been done on 20/mar/12.

    Standards compliance


    Unique ids and fixed 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 to have the fixed name. JSF 2.2 compatible libraries wanting to do something with the viewstate now have to work with a name-spaced Id (like other ‘normal’ elements in the markup rendered by JSF), or do lookups based on the name name attribute if they want to continue using the fixed name.

    For now, 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 had initially been marked as resolved, but was re-opened on 06/feb/12 because of complexities involving the notorious troublesome Portlets environment and a new commit was done on 09/feb/12. See the EG discussion for more details.

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


    Allowing id attribute on all elements for HTML5 content (spec issue 1100)

    Contrary to previous HTML standards, it’s allowed in HTML5 to use an id attribute for every kind of element.

    In JSF 2.1 and earlier, the id attribute on the head was not being rendered. In case HTML5 content is being served, JSF 2.2 will render the id attribute for this element. For previous versions of HTML this is not done. Additionally, the VDL docs were updated and now state that for the body element an id attribute is rendered as well (this already happened, but the docs didn’t mention it).

    Incidentally, a nice tidbit of information that we learned from this issue is that in JSF 2.2, HTML5 will be the default.

    Commits for this feature have been done between 14/may/12 and the associated issue has been marked as resolved.

    Cancelled features

    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. <ui:repeat value="#{someBean.items}" var="item">
    2.     <!-- item is in scope here -->
    3. </ui:repeat>
    4.  
    5. <!-- 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 would have introduced a ComponentModificationManager that could have been obtained via a call to FacesContext#getComponentModificationManager

    Although details remained scarce throughout the development (only an API draft had been committed), it’s possible the API might have been used by components as follows:

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

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

    The person who originally requested this feature for one reason or the other wasn’t able to give feedback about it when it was committed. When the feedback could finally be given, there was no time left, and the feature was asked to be removed and will likely be re-attempted for JSF 2.3.

    Commits for this feature have been done on 16/dec/11, but it was reverted on 14/mar/13.


    Component modification management (spec issue 763)

  • Injection in all JSF artifacts
  • The original goal of JSF 2.2 was to have support for injection into all JSF artifacts. This had at one point indeed been implemented, and could be used with most snapshot versions of JSF 2.2 that were published during its dev cycle.

    Unfortunately, at the very last moment it was discovered that there are some intricate subtleties involved with injecting into a UIComponent and its attached artifacts converter, validator and behavior.

    Following that discovery, injection into those artifacts was pulled at the very last moment (the proposed final draft still mentions them).


    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 had initially been given another great boost by making this factory obtainable from the FactoryFinder and moving it to the API part of JSF. The factory was for a while obtainable via the constant FactoryFinder.FACELET_FACTORY (javax.faces.view.facelets.FaceletFactory).

    A practically consequence of this was that it would have been possible to create a Facelet programmatically (in a portable way) and call the apply() method in order to build a component tree.

    Commits for this feature have been done on 15/sep/11 and the associated issue had been marked as resolved, but to great dispair of many the feature was removed again on 29/Nov/12 because it wasn’t possible to cleanly decorate it and there were thus leaking abstractions.


    That’s it for now! I’ll periodically update this page to cover additional JSF 2.2 items.

    Arjan Tijms

    54 comments to “What’s new in JSF 2.2?”

    1. JavaPins says:

      What’s new in JSF 2.2? | J-Development…

      Thank you for submitting this cool story – Trackback from JavaPins…

    2. What’s New in JSF 2.2 | Maxa Blog says:

      [...] Published by max on October 4, 2011 08:49 pm under JSF, RichFaces var addthis_product = 'wpp-262'; var addthis_config = {"data_track_clickback":false,"data_track_addressbar":false};var addthis_options = "twitter,facebook,google_plusone,dzone,print,email";if (typeof(addthis_share) == "undefined"){ addthis_share = [];}Find out what’s new in JSF 2.2. [...]

    3. Brendan Healey says:

      The greatest step forward for me in my use of JSF 2 has been the discovery of the
      MyFaces CDI extensions package (aka CODI) which amongst other things provides
      the incredibly useful @ViewAccessScoped. Forget cumbersome and insecure view
      parameters or entirely unreliable flash, when transitioning from one view to another,
      with view access scope you simply set a reference(s) in the target bean with
      setPropertyActionListener (or @Inject from backing bean) and the data you need to
      be there is where it should be.

      This really needs to get added to the spec as the new RequestScoped, in an ajax
      world, that is.

    4. Reply to Comparing Java Web Frameworks « henk53 says:

      [...] to continue it (obviously nonsense, since 2.1 has been released since and 2.2 is in progress, see What’s new in JSF 2.2?), and that James Gosling said he hated JSF (this was nonsense; it’s well known he meant to [...]

    5. Most interesting links of October « The Holy Java says:

      [...] though JSF 1 sucked, JSF 2 is really good (and still improving). Interesting links too (such as What’s new in JSF 2.2?). Corresponds to my belief that GWT and JSF are some of the best frameworks [...]

    6. Jonathan Fisher says:

      Excellent! JSF 2.2 needs two more things:

      * A BETTER WAY to handle ViewExpiredException, or when the user’s session expires!!!
      * A Better way to share complex JavaBeans between pages. MyFaces has @ViewAccessScoped, we need something like this in JSF 2.2

    7. arjan tijms says:

      >A BETTER WAY to handle ViewExpiredException, or when the user’s session expires!!!

      I definitely agree with that. I think this is part of the larger issue concerning state management in general, which is one of the last big architectural issues that’s still open.

      A few JIRA issues related to this:

      * http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1055
      * http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1056

      In particular, regarding the ViewExpiredException, there could maybe be some kind of hook where applications have the opportunity to recover from it. There are quite a few occasions where there really isn’t any state, or the state just concerns a disposable cache that can be rebuild from the source.

      >A Better way to share complex JavaBeans between pages. MyFaces has @ViewAccessScoped, we need something like this in JSF 2.2

      Since that’s a portable CDI extension (CODI), it should work with every JSF implementation. JSF already supports CDI (or rather the other way around), and is likely to deprecate the native managed bean facility in favor of CDI managed beans.

      But indeed, a few of such scopes could be standardized in core JSF, should it indeed formally move to CDI.

    8. alrom says:

      Is there any effort on visual web jsf designer for JSF 2.x?

    9. arjan tijms says:

      >Is there any effort on visual web jsf designer for JSF 2.x?

      This is largely an effort made by tooling that’s outside of the JSF 2.x spec itself. In the case of JSF, tooling and API are not really developed together like I think more or less happens with ASP.NET and Visual Studio.

      The JSF spec can offer some support so tooling has an easier job, but as far as I know nothing has been done for that in JSF 2.2 yet.

    10. Andreas Johansson says:

      Interesting article, even if I don’t use JSF every day its always nice to follow what’s going on and what to expect in upcoming releases. Great work!

    11. Les nouveautés de JSF 2.2 (JSR 344) > Patate-chaude says:

      [...] fort intéressant sur les nouveautés apportées par la future version de JSF, à savoir JSF 2.2. C’est ici ! Publié le février 15, 2012 par mathieu. Cet article a été publié dans Java, JSF, JSF-2. [...]

    12. Patate Chaude » Les nouveautés de JSF 2.2 (JSR 344) > Patate-chaude says:

      [...] fort intéressant sur les nouveautés apportées par la future version de JSF, à savoir JSF 2.2. C’est ici ! Publié le février 15, 2012 par mathieu. Cet article a été publié dans Java, JEE6, JSF, [...]

    13. George says:

      Great article, that gives a good view on whats in the making. Will you post an update soon?

    14. arjan tijms says:

      Thanks George :)

      I’m continuously updating this article instead of posting new updates. I guess it would be clearer if I put a last updated data somewhere. The current version was last updated 7 March, so it’s approximately 2 weeks old.

      I’ll update it again soon though. Thanks again for your interest.

    15. Paul M says:

      Hi, Its really great to see JSF grow. I just have two comments

      1)The biggest one for me is fix for ViewScope. I believe this is critical feature that should be back-ported to other 2.0 since JSF users/developers can leverage MVP pattern better.
      2) As current user-developer for JSF there is a Major things missing
      a) JSF own WebFlow Controller (I know this exists in Spring WebFlow but there are integration issues especially with Facelets for composite components)
      b) JSF own Conversation and Flow Scopes to support WebFlow concept.

      Thank you.

    16. arjan tijms says:

      Paul, I’m afraid chances of the view scope changes being ported back to 2.0 are slim at best. It’s a spec breaking change, and those are rarely back ported. I agree that it fixes some critical problems though. See http://java.net/jira/browse/JAVASERVERFACES-1492 for additional info and https://issues.jboss.org/browse/JBSEAM-4898 for an additional issue.

      As for 2), there happens to be an effort going on for this for JSF 2.2. As there weren’t any commits being done for it I didn’t write about it yet. See this http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-730

    17. JSF 2.2 Update from Ed Burns « oracle fusion identity says:

      [...] blog at J-Development provide complete details about the new features coming in this version. And an Early Draft of the [...]

    18. JMS 2.0 Early Draft – Simplified API Sample Code « oracle fusion identity says:

      [...] What’s new in JSF 2.2 ? (external contribution) [...]

    19. JSON-P: Java API for JSON Processing (TOTD #178) « oracleidentitymanagement says:

      [...] What’s new in JSF 2.2 ? [...]

    20. How do I use a java.util.Set with UIData in JSF. Specifically h:datatable? | PHP Developer Resource says:

      [...] easier, support for Set (actually, the entire Collection interface) in DataModel is available in JSF 2.2. It’s currently already available as snapshot so that you can just start [...]

    21. ui:repeat inside ui:repeat | PHP Developer Resource says:

      [...] <ui:repeat> doesn’t support Set<E>. This support will be introduced in the upcoming JSF 2.2 (also for <h:dataTable>). JSF 2.2 will be released this quarter [...]

    22. Ashley Westwell says:

      Hello All,

      I would make a feature request to be able to support ui:iclude at the view layer. Support should be there to do an EL for the value of a ui:include. AN example is attempting to do a ui:include inside a ui:repeate. As you know the ui:include is currently only supported at the build tree compent level. Which means you can not do a dynamic include at the redender scope level. I would suggest that you add a scope attribute on ui:include so you can switch based on requirements.

    23. arjan tijms says:

      That’s an interesting functionality for sure Ashley. This article however is about changes in JSF 2.2. that have already been committed, a better place for official feature requests would be the JIRA for the JSF spec, which you can find at:

      http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC

      Alternatively, you can create an issue at the OmniFaces project, where I and my co-worker Bauke focus on these kinds of utility functionalities. You can find this at:

      http://code.google.com/p/omnifaces/issues/list

    24. John Yeary says:

      This is an incredibly well written article. I have really enjoyed a number of articles that are posted on your blog. Keep up the great work! I am excited to see 2.2

    25. arjan tijms says:

      Thanks John, nice to hear you appreciated the article :)

    26. Ove Ranheim says:

      Is there any updated release schedule for 2.2? I really like the idea of ‘Big Ticket Features’ and hope the JCP and endorse it! It’s about a year since Ed was in on Seam IRC gathering inputs. Now, I look forward to start making use of all these nice features coming along.

      Two Big Tickets for me are: flows and sensible html5 support.

      Can’t wait to see this get out the door :)

    27. Michael Kurz says:

      Very nice work Arjan, thanks. One minor issue: The state serialization issue seems to be issue 1127 and not 1217.

    28. arjan tijms says:

      Wow, I somehow messed that one up. Thanks for the hint Michael, fixed it right away!

    29. Lo nuevo en JSF 2.2 | Notas de Arquitectura y Desarrollo de Software says:

      [...] http://jdevelopment.nl/jsf-22/ [...]

    30. 10 razões para migrar sua aplicação para JSF 2 | blog.caelum.com.br says:

      [...] do @ViewScope com a combinação JSF + CDI, já estão previstos para serem resolvidos no JSF2.2, assim como melhorias no suporte ao HTML5, AJAX e navegação com o Faces Flow e outros itens [...]

    31. Mite Mitreski says:

      Pass-through attributes, look like a very cool feature.

    32. Björn Raupach says:

      Thanks you very much for the informative article.

    33. Java EE: JSF 2.2(JSR 344) – versão Draft Disponível « Paulo Borges aka poolborges says:

      [...] What’s new in JSF 2.2 [...]

    34. Elias says:

      Hello, Arjan, thanks for this great writeup!

      I’m not very familiar with CDI (more used to Spring — that’s what I use at work), so I have this one question about the possible change relating @ViewScope:

      Does the fact that the CDI @ViewScoped bean remain active even for new GET requests means that when the user open new tabs for the same view he will get the same scope?
      Won’t this cause the same problems that using the backing beans in session scope, turning new GET requests less repeatable?

    35. jik le shoog says:

      Is jsf 2.2 going to give developers the option of stateless views or not?

    36. Arjan Tijms says:

      Is jsf 2.2 going to give developers the option of stateless views or not?

      Yes, JSF 2.2 will have a per-view stateless option. I’m a bit behind in updating this article, but I’ll soon try to catch up and add info about this. For now read about the details here: http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1055

    37. jik le shoog says:

      Arjan,

      Thank you so much for this post and for all your contributions on Stackoverflow. I find them some of the most competent I could find. I always suffered from not finding good documentation for JSF, other than the spec, which is pretty dry sometimes. For me, you are Mister JSF Beacon! :)

      jik le shoog

    38. jik le shoog says:

      Is there a JSF way to solve the back button issue in the browser?

    39. Conheça as principais novidades no JavaEE 7 | blog.caelum.com.br says:

      [...] Além destas, ainda há uma integração melhor com HTML5, suporte a configuração programática, um novo componente para upload de arquivos usando ajax, e muitas outras, como é possível ver na lista de novidades no JSF 2.2 [...]

    40. JavaEE 7 exemplos e novidades! | Revolução Java says:

      [...] Além destas, ainda há uma integração melhor com HTML5, suporte a configuração programática, um novo componente para upload de arquivos usando ajax, e muitas outras, como é possível ver na lista de novidades no JSF 2.2 [...]

    41. Rodmar CONDE says:

      Excellent article!!! It allows to get involved into the complexity of today’s systems. Why building web pages became as complex as this!!! =)

    42. JSF 2.2 (JSR-344) のダウンロード | フリーソフトstartnews24 says:

      [...] Views (see this excelent explanation by Arjan Tijmes: http://jdevelopment.nl/jsf-22/?topic=stateless#1055 and BalusC’s [...]

    43. Hantsy says:

      Personally, a little disappointed about the cancellation of the injecting to jsf artifacts, which is my long waiting features in JSF 2.2. Why not work together with the CDI exports to resolve the problems.

      When I used JSF 2.1 and CDI in Java EE6, there are many problems if used CDI bean as JSF backend bean, especially from the “Paritial State Holder” exception in Ajax, I have to disable PARTIAL_STATE_SAVING to avoid the problems, but lack some features of JSF/Richfaces4, I remember there is a page described this in Richfaces project before, and “Partial State” problem is a long problem in the JSF complained by developers.

      I think make all the specs work seamless is the most thing, then is bringing the new features.

      The resource library contract or the theme/template concept are supported by many JSF Components project, I do not think it is the responsibility of JSF spec.

      The Flow is most inspired by Oracle ADF, not seam2 or Spring WebFlow. A CDI @ConversationScoped can be reused, but a new @FlowScoped is invented.

    44. Arjan Tijms says:

      Why not work together with the CDI exports to resolve the problems.

      I think they would have done that if only the issue was discovered earlier and more of the community weighed in to express that this feature was important.

      As it stands, Manfred discovered the issue relatively late (so there was very little time to fix it). Ed Burns asked the community how to proceed, but there wasn’t a lot of response. It would have maybe helped if you posted a reply on the JSF mailing list like you just did here, but unfortunately it’s too late for that now.

      I’m sure though that JSF 2.3 (perhaps a MR again like 2.1 was) will focus on getting this fixed. Everyone agrees it’s a very important feature.

      I have to disable PARTIAL_STATE_SAVING to avoid the problems, but lack some features of JSF/Richfaces4,

      I’m not 100% sure what you are referring to here, but I’ve got a feeling this is some RichFaces specific issue and not a general JSF 2 issue. Or do you have some pointers (perhaps JIRA issues?) that explain this? Thanks!

    45. Goodbye, JSF! | hopeful ramble says:

      [...] vindo aí no JSF 2.2 o suporte a Stateless Views (basicamente, páginas que não precisem de armazenar a árvore no [...]

    46. JavaEE 7 最全教程集锦 | Java,go's的个人博客 says:

      [...] What’s new in JSF 2.2? [...]

    47. JSF 2.2: Novidades para desenvolvimento HTML5 | Blog R-Sys Softwares says:

      [...] versão 2.2 do JSF traz várias outras mudanças menores. O artigo de Arjam Tijms no site J-Development inclui outros [...]

    48. Some May tips | codeplay says:

      [...] http://jdevelopment.nl/jsf-22/ [...]

    49. Was gibt es neues in JSF 2.2? - Java Blog | Javainsel-Blog says:

      [...] Schon älter, aber prima Details: http://jdevelopment.nl/jsf-22/?220112. [...]

    50. Mike says:

      Thanks for the tutorial – one remar, the passthrough namespace got changed with 2.2 (final) from http://java.sun.com/jsf/passthrough to http://xmlns.jcp.org/jsf/passthrough

    51. Bruno says:

      I would like to know if it is possible to exit a faces-flow navigating to an arbitrary view, and not to the exits point defined in the flow config.

      I ask that because I want to be able to “kill” my flow if the user click another link that has nothing to do with the flow (another item in the menu for example)…

    52. @ViewScoped, o ovo e a galinha | Rafael Ponte says:

      [...] não estavam acostumados, como problemas de serialização, escopo restrito apenas a mesma página, integração precária com CDI e Spring, incompatibilidade com JSTL e a necessidade de limpar a todo instante os dados do managed [...]

    53. [JSF] PrimeFaces: una tecnologia di front-end che si sta imponendo nel mercato Enterprise says:

      [...] Prime Faces: implementazione dello standard Java Server Faces – JSF 2.2; [...]

    54. Security threat – Cross site request Forgery (CSRF) | Secure By Default says:

      […] Note that JSF 2.0 already took some action covering CSRF. However, the CSRF-protection in JSF 2.0 is implicit and is only valid for POST requests. In JSF 2.2 there will be more explicit support for this. I briefly explained this here: http://jdevelopment.nl/jsf-22/ […]

    Type your comment below:


    3 + one =

    css.php best counter