What’s new in JSF 2.2?

10 April 2012, by: arjan tijms

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

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

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

Download

The milestone 1 release that contains a lot of functionality implemented before ~March 2012 can be downloaded here.

New features

GET Support


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

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

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

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

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

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

A very simple example:

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

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

Navigation


Faces Flow (spec issue 730) (mentioned in JSR)

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, most likely using the name Faces Flow.

Faces Flow is a rather big new 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 initial commit has the following JavaDoc:

Classes with this annotation attached to them will be considered to be in the scope of the named 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 named flow, and de-allocated when the user exits the named flow.

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

A flow scope bean will look something like this:

@Named
@FlowScoped(name="someFlowName")
public class SomBean {
    // ...
}

A new element has been introduced for faces-config.xml: faces-flow-definition. At the moment it’s not yet clear how this will be used, but the current skeleton form looks like this:

<faces-config version="2.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_2.xsd">
 
    <faces-flow-definition>
 
    </faces-flow-definition>
 
</faces-config>

Holding up the design philosophy that as many things as possible should not require configuration in faces-config.xml, it will also be possible to put the flow definition directly into the artifacts that make up a flow. For instance, in a view the metadata element will be leveraged:

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

Notice the addition of a new taglib URI in core JSF: http://java.sun.com/jsf/flow. This new taglib has the following description:

Specify how a flow is declared in VDL pages. This schema is functionally equivalent to the same content in a faces-config.xml file.

As of now, the following tags have been placed in that lib:

  • faces-flow-definition
  • default-node – (Gets name of this page without any extension)
  • view
  • vdl-document – (Gets name of this page with the extension)

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 or transition to a new point in the flow. A Flow can among others be asked for the Id relative to the current window. This currently consists of the Window Id and the Flow Id separated by an underscore.

At the time of writing, the implementation is only in a very early stadium and various things have not been implemented yet.

Commits for this feature have been done between 29/mar/12 and 10/apr/12.

AJAX


Queue control for AJAX requests (spec issue 1050)

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

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

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

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

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


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

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

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

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

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

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

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


Injection / Annotations


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

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

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

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

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


Facelets 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://java.sun.com/jsf/component’ will be used.

For instance:

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

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


FaceletFactory in the standard API (spec issue 611)

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

In JSF 2.2, the status of Facelets as a default technology within JSF has been given another boost by making this factory obtainable from the FactoryFinder and moving it to the API part of JSF. The factory is obtainable via the constant FactoryFinder.FACELET_FACTORY (javax.faces.view.facelets.FaceletFactory).

Commits for this feature have been done on 15/sep/11 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
2
3
<factory>
    <flash-factory>com.example.MyFlashFactory</flash-factory>
</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 (spec issue 599)

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

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

JSF 2.2 will provide an explicit API for this.

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


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

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

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

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

The following are now the supported types:

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

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

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


Wrapper class for Lifecycle

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 ViewHandlerWrapper, StateManagerWrapper for StateManager, etc.

Until now there wasn’t a wrapper class for LifeCycle. In JSF 2.2 there now is, with the predictable name LifeCycleWrapper :)

This small feature didn’t had a separate JIRA issue, but was committed as part for the work for spec issue 949.

Commits for this feature have been done on 23/feb/12.

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 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.WINDOW_ID_MODE</param-name>
    <param-value>field</param-value> 
</context-param>

The current draft implementation supports only field and none which is the default. Additional anticipated values are script and url.

The window Id currently consists of the session Id (JSESSIONID) followed by separator and a sequential number, e.g. 953FAAGhGhYF78:1. The draft uses a hidden field with the name “javax.faces.WindowId”.

There are various places where the window concept will appear in the API, but most visible will be the new class 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. 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 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 29/feb/12.


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

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

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

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

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

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


System events for The Flash (spec issue 766)

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

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

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

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

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


Publish PostRestoreStateEvent (spec issue 1061)

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

Components


Component modification management (spec issue 984)

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

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

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

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

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

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

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

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

XML configuration


Case insensitivity for state saving method (spec issue 1010)

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

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

Standards compliance


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.

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

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

Arjan Tijms

19 Comments on “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 ? [...]

Type your comment below:

best counter