What’s new in JSF 2.2?
22 January 2012JSF 2.2 is currently in its early stages of development, and originally had an anticipated release of the final draft of the spec in Q4 2011 (see Jsf 2 2-bof, slide 3 and JSR 344: JavaServer Faces 2.2). This date slipped, but we might still see the actual release somewhere in the first half of 2012.
So what’s going to be in 2.2? The JSR gives an overview of ideas, but explicitly makes the reservation that not all of those will be in the final spec. So, another source worth looking at is the actual trunk of the reference implementation and its associated implementation JIRA as well as that of the public specification JIRA.
In this post I’ll try to highlight some items from that activity that I found interesting. Note that all of this is preliminary and just reflects the activity in the trunk, not what is absolutely promised to be in the final JSF 2.2 specification. Of course, if there’s a lot of activity and commits for some item, there’s a rather high chance that it will indeed end up in the spec.
Contents
- GET Support
- AJAX
- Injection / Annotations
- Security / Type-safety
- Java API
- Lifecycle
- Components
- XML configuration
- Standards compliance
GET Support
View Actions (spec issue 758) (mentioned in JSR)
JSF 2.0 made GET requests a first class citizen in JSF and brought it almost on par with the existing POST support. Just as after a post-back, request values from a GET request can be bound to a model and converters and validators can be applied to that binding.
However, JSF 2.0 didn’t specify an associated action method. A preRenderView event listener can be used instead and that actually does work for a lot of use-cases, but it’s not at the same level as normal action methods that are invoked after a POST request. Users have to manually interact with the NavigationHandler and since the listener is invoked before every rendering, users have to programmatically check if the request was a GET request or a post-back.
View actions are going to allow the same kind of action methods that are used for post-backs to be useable via a new metadata element called <f:viewAction>. The Seam 3 component with the same name was an important inspiration for this.
An additional advantage of a view action is that it can be processed before the entire component tree is being build. Only the meta data needs to be present, which is normally build separately from the rest of the tree.
The feature is discussed in more detail together with sample code at: New JavaServer Faces 2.2 Feature: The viewAction Component
A very simple example:
1 2 3 | <f:metadata> <f:viewAction action="#{someBean.someAction}" /> </f:metadata> |
Commits for this feature have been done between 16/jun/11 and 18/aug/11.
AJAX
Queue control for AJAX requests (spec issue 1050)
The standard AJAX support in JSF causes AJAX requests to be queued client-side to make sure a page has only 1 such request in transit at the same time.
This is normally beneficial, as it prevents the server from being overloaded and responses arriving out of order. Typical features here are specifying the maximum size of the queue or the amount of time a request is allowed to sit waiting in the queue.
However, JSF lacked those features. Werner Punz wrote about this recently: Apache MyFaces jsf.js queue control.
JSF will add support for controlling the queue by means of a delay attribute on the <f:ajax> tag. This attribute takes a value in milliseconds and signals that if multiple requests arrive within this delay period, only the most recent one is sent to the server. The default is 300 milliseconds, but the special value of none can be specified to disable this mechanism.
Commits for this feature have been done on 10/jun/11 and the associated issue has been marked as resolved.
AJAX file upload component (spec issue 802) (mentioned in JSR)
Having a (AJAX) file upload component in JSF goes back a long time. There is much existing discussion on this issue, and many component libraries have in the mean time implemented something themselves.
An AJAX variant is even more difficult, not in the least since it’s not directly supported in HTML. There’s an iframe based trick available, but this by itself does not work directly with JSF. To support this, changes are required to the mechanism that triggers a JSF request/response cycle.
A prerequisite to an AJAX file upload mechanism is having a standard file upload in JSF. For this a separate issue was created: Non-Ajax File Upload. Interesting here is that this implementation is based on Servlet 3.0 multipart support, like e.g. this implementation by my co-worker Bauke. This means among other that the venerable FacesServlet is now annotated with the @MultipartConfig annotation and that JSF now requires Servlet 3.0.
The standard file upload component can be used on a view as follows:
1 2 3 4 5 6 7 | <h:form prependId="false" enctype="multipart/form-data"> <!-- The new regular file upload component --> <h:inputFile id="fileUpload" value="#{someBean.file}" /> <h:commandButton value="Upload" /> </h:form> |
Commits for the sub-issue have been done on 15/dec/11.
Injection / Annotations
Injection in all JSF artifacts (spec issue 763) (mentioned in JSR)
In JSF 2.1, relatively few JSF artifacts are injection targets for EJB (@EJB, @Resource), CDI (@Inject) or JSF’s native injection mechanism. Basically only managed beans (backing beans) are injection targets.
This poses a problem for e.g. converters and validators, which not rarely need an EJB service to do their work. For instance, an incoming user ID from a GET request might needs to be converted to a User instance via the Stateless EJB UserService. There are some workarounds for this as outlined in this excellent guide from my co-worker Bauke, but they ain’t pretty.
In JSF 2.2 injection will be possible in converters, validators, components, behaviors and much more artifacts.
Commits for this feature have been done between 27/aug/11 and 31/oct/11 and the associated issue had been marked as resolved, but on 11/jan/12 an additional commit was done that changed how the InjectionProvider is internally obtained by the FactoryFinder.
Facelets ResourceResolver can be declared via annotation (spec issue 1038)
In Facelets it has always been possible to let users provide a hook to influence the way that Facelets loads template files. This is done via a ResourceResolver that users can register in web.xml via the environment parameter javax.faces.FACELETS_RESOURCE_RESOLVER.
With such a resolver, users can let Facelets load templates from the classpath or from any location that is expressible via a URL.
The web.xml mechanism however pre-dates the time that Facelets was officially part of JSF itself and it of course requires the presence of such a web.xml file. Since Facelets is now officially part of JSF and there is a strong trend going to make XML optional in favor of annotations, the Facelets resource resolver has now gotten an official annotation in the JSF spec:
@FaceletsResourceResolver.
The presence of that annotation on a class automatically registers it as a Facelets resource resolver. If a resolver is specified in both XML and via an annotation, the XML overrides the annotation as per the usual Java EE conventions. If multiple annotated classes are found, the first one encountered is used and a warning is logged.
Commits for this feature have been done between 06/oct/11 and 12/oct/11 and the associated issue has been marked as resolved.
Security / Type-safety
Cross Site Request Forgery protection (spec issue 869) (mentioned in JSR)
Cross Site Request Forgery is an attack that lets users unknowingly do a request to a site where they are supposed to be logged-in, that has some side-effect that is most likely in some way beneficial to the attacker. GET based requests are most obvious here, but POST requests are just as vulnerable.
JSF seems to have some implicit protection against this when state is saved on the server, since a post-back must contain a valid javax.faces.ViewState hidden parameter. Contrary to earlier versions, this value seems sufficiently random in modern JSF implementations.
Nevertheless, JSF 2.2 will contain additional/even stricter protection against this. Among others client state encryption is now on by default and there’s a token parameter for protection of non-postback views.
Commits for this feature have been done between 13/sep/11 and 21/sep/11.
More thorough type checking for composite component attributes (spec issue 745)
In JSF 2.1, it’s not always easy to defer the exact type of a value expression bound to an attribute of a composite component, if said expression resolves to null. Finding the right type just by asking ElResolver is complicated by the fact that ELResolver#getType is supposed to return the most general type that is accepted by the corresponding ELResolver#setValue. It’s also not always equal to getValue().getClass() as explained by the javadoc.
In JSF 2.1, CompositeComponentAttributesELResolver#getType returned null when asked for the type, since it’s a read only resolver.
For JSF 2.2 this is replaced with an algorithm that first checks if the base is an ExpressionEvalMap and if so simply gets the value expression from that and asks it for its type. Then the metadata for the composite component is consulted to see if there’s a type being set for the given attribute (this corresponds to the type attribute on the cc:attribute tag). Finally, if a type is found via the metadata it’s only used if the type obtained from the value expression is either null, or if the metadata type is more specific (narrower).
Commits for this feature have been done between 20/jul/11 and 10/aug/11.
Java API
FaceletFactory in the standard API (spec issue 611)
JSF has a facility for obtaining factories for various things via the FactoryFinder. Even though Facelets is a standard part of JSF since 2.0, the FaceletFactory could not be obtained this way as it was an implementation detail.
In JSF 2.2, the status of Facelets as a default technology within JSF has been given another boost by making this factory obtainable from the FactoryFinder and moving it to the API part of JSF.
Commits for this feature have been done on 15/sep/11 and the associated issue has been marked as resolved.
Instantiating composite component in Java (spec issue 599)
JSF 2.0 introduced the concept of the composite component: a component that is created via an .xhtml template instead of Java code. Even though the composite component is defined in .xhtml, it’s a first class component and ends up in the component tree as a Java component.
Up till now however there wasn’t any official API to instantiate a composite component as a Java instance via user code. So when building a component tree programmatically (see e.g. Authoring JSF pages in pure Java), incorporating those composite components was challenging to say the least.
JSF 2.2 will provide an explicit API for this.
Commits for this feature have been done between 02/oct/11 and 04/oct/11 and the associated issue has been marked as resolved.
Support for the Collection interface in UIData (spec issue 479) (mentioned in JSR)
From the beginning of JSF, the UIData component (known from e.g. <h:dataTable>) only realistically supports the List, native array and JSF specific DataModel as input for its value binding*. This means other collection types always have to be expressed as any of these types. While this is not particular difficult, it’s a tedious thing to do and makes the code more verbose.
This issue has a rather long history, but it’s now finally addressed.
JSF 2.2 will introduce a javax.faces.model.CollectionDataModel in which UIData wraps an incoming value if it’s of type Collection. Collection is one of the last types being checked, so if the incoming value is a List the ListDataModel takes precedence.
The following are now the supported types:
- null (becomes empty list)
- javax.faces.model.DataModel
- java.util.List
- java.lang.Object[]
- java.sql.ResultSet
- javax.servlet.jsp.jstl.sql.Result
- java.util.Collection new!
- java.lang.Object (becomes ScalarDataModel)
Commits for this feature have been done on 31/jan/12 and the associated issue has been marked as resolved.
* java.sql.ResultSet and javax.servlet.jsp.jstl.sql.Result are officially also supported, but it seems usage of those are rather rare in practice. Also, only DataModel is internally supported, other types are automatically adapted into a DataModel.
Lifecycle
Restoring view scope before view is build (spec issue 787)
In JSF 2.0 a new scope called the view scope was introduced. The life-time of this scope is coupled to that of the view state associated with the component tree for a given view. As such it’s easy to just store the data in this scope along with the view state and restore it whenever view state is restored, which happens right after the view has been build.
However, for some advanced usages it’s more convenient to have the view scope restored before the view is build again. As a very contrived example, the bean Intro from the code shown in Single class pure Java JSF application could not be view scoped, since the view scope doesn’t exists at the time the view needs to be build.
Disentangling the view scope from the general view state data actually has other benefits as well, e.g. users could provide alternative handlers for the view scope, something which is not possible or at least very difficult and not portable at the moment.
Currently a new method (UIViewRoot#restoreViewScopeState(FacesContext context, Object state)) to restore only ViewScope has been committed. A separate effort is planned for JSF 2.2 to also create the corresponding saveViewScopeState, but as of yet nothing has been committed for that.
Commits for this feature have been done between 9/jun/11 and 27/jul/11 and the associated issue has been marked as resolved.
System events for The Flash (spec issue 766)
JSF 2 introduced the concept of system events, which are events that can be fired by arbitrary objects at arbitrary points during the request processing lifecycle.
In the current version JSF 2.1 there are some 16 events defined, e.g. PostAddToViewEvent, PostConstructViewMapEvent, PreRenderViewEvent, PreValidateEvent, etc.
JSF 2.2 will fire 4 additional events specifically for usage with The Flash. These are:
- PostKeepFlashValueEvent – Fired when a value is kept in The Flash
- PostPutFlashValueEvent – Fired when a value is stored in The Flash
- PreClearFlashEvent – Fired before The Flash is cleared
- PreRemoveFlashValueEvent – Fired when a value is removed from the Flash
Commits for this feature have been done between 28/oct/11 and 31/oct/11.
Publish PostRestoreStateEvent (spec issue 1061)
Normally system events in JSF are fired/published via the Application#publishEvent API.
However in JSF 2.1 and before, PostRestoreStateEvent has been an exception to this rule. The problem is that this event must be delivered to all UIComponents. Requiring the use of the publish API for this is sub-optimal with respect to memory requirements, since it would also require every component to return a list with itself as a listener when UIComponent.getListenersForEventClass() is called.
Earlier versions of JSF therefor delivered the event directly to the components using a tree traversal, but this meant it was not possible to install any listeners for this event.
In JSF 2.2 this problem was solved by simply doing both the event publishing (without making UIComponents default listeners) AND doing the traditional tree traversal. In Mojarra, the event is published first and then the tree traversal starts.
Commits for this feature have been done on 15/dec/11.
Mandate tree visiting for partial state saving (spec issue 1028)
In order to implement the partial state saving feature of JSF, an implementation must somehow look at all components in the component tree and ask them for their (partial) state.
The exact way in which this is done was implementation specific in JSF 2.1 and earlier. Mojarra used a tree visiting algorithm for this, while MyFaces used a so-called “facets + children” traversal.
The differences between those two are somewhat technical, but one of them is that tree visiting allows the algorithm for the actual traversal to be plugged-in (strategy pattern), while the “facets + children” traversal doesn’t allow this (the code accesses the list of children of a component directly and iterates over it).
Another major difference is that tree visiting is “in context” (parent component can set up a context/scope before its children are visited), while “facets + children” traversals just follow a ‘dumb’ pointer structure.
Finally, tree visits have the ability to visit “virtual components” created by iterating components like UIData. (for a typical JSF data table, there is no component per row in the tree, but the UIData creates this illusion by swapping state in and out for each row).
For state saving, this are somewhat conflicting properties. Setting up a context and doing iterating over virtual children is unwanted, but influencing the traversal can be important. JSF 2.1 introduced the IS_SAVING_STATE and SKIP_ITERATION hints, which can undo the unwanted effects, while keeping the ability to influence the traversal.
In JSF 2.2, tree visiting will now be mandated for partial state saving. StateManager#saveView and StateManager#restoreView have been deprecated in favor of methods with the same name in StateManagementStrategy, for which implementations are now required to use the visit API (UIComponent#visitTree), e.g. as-in the simplified example:
1 2 3 4 5 6 7 8 9 10 11 | viewRoot.visitTree(visitContext, new VisitCallback() { public VisitResult visit(VisitContext context, UIComponent target) { if (!target.isTransient()) { savedState.put( target.getClientId(context.getFacesContext()), target.saveState(context.getFacesContext()) ); } return ACCEPT; } }); |
(This is a rather advanced feature that the average JSF application developer will not likely come in contact with.)
Commits for this feature have been done on 22/dec/11.
Components
Component modification management (spec issue 984)
In JSF, components can introduce variables in a kind of “component scope” or “component context”. The var attribute of iterating components like UIData or UIRepeat is a well known example of this. E.g.
1 2 3 4 5 | <ui:repeat value="#{someBean.items}" var="item"> <!-- item is in scope here --> </ui:repeat> <!-- item no longer in scope --> |
In JSF 2.1 and before there is no explicit API that components can use to manage this context. This is potentially troublesome for components that need to do a full tree visit within a clean context.
To assist with managing this context, JSF 2.2 will introduce a ComponentModificationManager that can be obtained via a call to FacesContext#getComponentModificationManager
Although details are scarce at the moment (only an API draft has been committed), it’s possible the API might be used by components as follows:
1 2 3 4 5 6 7 8 9 10 | public boolean visitTree(VisitContext visitContext, VisitCallback callback) { ComponentModificationManager manager = visitContext.getFacesContext().getComponentModificationManager(); ComponentModification modifications = manager.suspend(visitContext.getFacesContext()); try { return super.visitTree(visitContext, callback); } finally { manager.resume(visitContext.getFacesContext(), modifications); } } |
(This is a rather advanced feature that the average JSF application developer will not likely come in contact with.)
Commits for this feature have been done on 16/dec/11.
XML configuration
Case insensitivity for state saving method (spec issue 1010)
In JSF one can set whether state is saved on the server or on the client via the context parameter javax.faces.STATE_SAVING_METHOD in web.xml which can be set to “server” or “client”. The values had to be used exactly as given. Using “Client” or “CLIENT” would actually result in server state saving being used. As of JSF 2.2 the value is made case insensitive, so those preferring to use “Client” can now do so.
Commits for this feature have been done on 26/may/11 and the associated issue has been marked as resolved.
Standards compliance
Using only name attribute for view state field (spec issue 220)
For keeping track of state associated with forms, JSF implementations write a hidden input field in each form that’s used on a page.
In JSF 1.2 this field was standardized and the specification demanded that both the id and name attributes were set to javax.faces.ViewState*.
The rule however breaks “W3C XHTML 1.0 Transitional” and above standards compliance. Namely, per that standard the id attribute should be globally unique within a document. If the JSF spec mandates that it should always have a fixed value, it clearly can’t be unique if multiple forms are being used on a single page.
Very early on, Mojarra introduced the parameter com.sun.faces.enableViewStateIdRendering, that when set to false simply omitted rendering the id attribute (thus leaving only the name present). Since this is an implementation specific parameter, not all third party libraries necessarily take its effects into account.
Therefor from JSF 2.2 on only the name attribute is mandated and JSF 2.2 compatible libraries should no longer assume anything about an id attribute being available. In addition, Mojarra has removed the com.sun.faces.enableViewStateIdRendering parameter completely, so setting this explicitly to true will not bring the id attribute back.
Commits for this feature have been done on 30/jan/12 and the associated issue has been marked as resolved.
*In addition the spec strongly recommends, though doesn’t enforce, that the value of this input field is difficult to predict in order to prevent cross site scripting attacks, see Cross Site Request Forgery protection for more details.
That’s it for now! I’ll periodically update this page when new information comes in.
Keep in mind that there are quite some interesting other things under discussion or even in development for possible inclusion in JSF 2.2. Such development is only currently taking place outside of the JSF trunk, which is the focus of this article. For instance see the discussion about a Window-id which is prototyped in MyFaces/CODI where a proposal is being setup as well, or the one about a multi-templating system (skinning), which is prototyped by lamine ba and mentioned by spec lead Ed Burns in an interview (among with several other interesting things, like HTML5 support).
Arjan Tijms






