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:

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

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

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.

Latest 2.2 release version (scroll down and look for latest 2.2.x version)

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.

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.

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:

Further reading:

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



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 has the following JavaDoc:

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:

The value someFlowName references the name of the flow this bean will back. Flows itself are defined via 3 conventions:A minimal flow configuration has to define 1 exit condition using the following syntax:

/someFlowName/someFlowName-flow.xml:

(note that the faces-config.xml format is (re-)used here)

Via the <initializer> and <finalizer> sub-elements of the <flow-definition> element 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.

<view id="intermediateNode"> <vdl-document>/someFlowName/intermediateNode.xhtml</vdl-document> </view>

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

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

Everything that can be defined via the -flow.xml configuration files can also alternatively be specified using a programmatic API.

Besides an @FlowScoped bean, there's also a new implicit EL variable introduced that's associated with the current flow: flowScope. 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="#{flowScope.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/> #{flowScope.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:

<faces-config version="2.2" 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"> <flow-definition> <initializer>#{someBean.init}</initializer> <start-node>startNode</start-node> <switch id="startNode"> <navigation-case> <if>#{someBean.someCondition}</if> <from-outcome>fooView</from-outcome> </navigation-case> </switch> <view id="barFlow"> <vdl-document>barFlow.xhtml</vdl-document> </view> <view id="fooView"> <vdl-document>create-customer.xhtml</vdl-document> </view> <flow-return id="exit"> <navigation-case> <from-outcome>/exit</from-outcome> </navigation-case> </flow-return> <flow-return id="error"> <navigation-case> <from-outcome>/error</from-outcome> </navigation-case> </flow-return> <finalizer>#{someBean.finish}</finalizer> </flow-definition> </faces-config>

An instance of the Flow class is basically the run-time representation of the 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.

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:

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

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>

<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

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

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>

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

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



Pass-through elements (spec issue 1111) (Big Ticket Feature)

An important aspect of JSF is that it's based on a set of components that represent the (HTML) UI elements that will eventually be rendered. In order to assemble these components together (into a tree structure) there are various general options, including:

Using a component specific format, e.g. using XML or a view specific DSL Using the same format as the target markup (if the target is markup of course) Programmatic, using plain Java to instantiate and wire components together

The second option means that in case HTML is rendered (which is nearly always the case when JSF is used) the component tree is specified using plain HTML tags, with a special attribute that links the tag to a component. JSF users could program using this paradigm ever since Facelets was introduced, and it automatically became available to all JSF users when the spec adopted Facelets with the release of JSF 2.0.

The programmatic variant has been implicitly supported since the very first version of JSF. The very same low-level API that the higher level "view description languages" are using is also available to the application programmer. It's normally used to dynamically modify a view that was build using such higher level language, but with some helper code it can be used to build views from scratch as well.

The following gives examples of the same component tree being constructed in those 3 ways: Component specific format: Facelets

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <body> <h:form> <h:outputText value="Welcome, #{loggedInUser.name}" /> <h:inputText value="#{bean.property}" /> <h:commandButton value="OK" action="#{bean.doSomething}" /> </h:form> </body> </html> </pre> <b>Target language format: HTML with special attribute</b> <pre class="brush: xml;"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <body> <form jsfc="h:form"> <span jsfc="h:outputText" value="Welcome, #{loggedInUser.name}" /> <input type="text" jsfc="h:inputText" value="#{bean.property}" /> <input type="submit" jsfc="h:commandButton" value="OK" action="#{bean.doSomething}" /> </form> </body> </html>

Programmatic: Native component API with JavaVDL helper code public class Demo implements Page { @Override public void buildView(FacesContext context, UIViewRoot root) throws IOException { ELContext elContext = context.getELContext(); ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory(); List rootChildren = root.getChildren(); UIOutput output = new UIOutput(); output.setValue("<html xmlns="http://www.w3.org/1999/xhtml">"); rootChildren.add(output); HtmlBody body = new HtmlBody(); rootChildren.add(body); HtmlForm form = new HtmlForm(); body.getChildren().add(form); ValueExpression messageProperty = expressionFactory.createValueExpression(elContext, "Welcome, #{loggedInUser.name}", String.class); HtmlOutputText message = new HtmlOutputText(); message.setValueExpression("value", messageProperty); form.getChildren().add(message); ValueExpression inputProperty = expressionFactory.createValueExpression(elContext, "#{bean.property}", String.class); HtmlInputText input = new HtmlOutputText(); input.setValueExpression("value", inputProperty); form.getChildren().add(message); MethodExpression actionMethod = expressionFactory.createMethodExpression(elContext, "#{bean.doSomething}", Void.class, new Class[0]); HtmlCommandButton command = new HtmlCommandButton(); command.setActionExpression(actionMethod); command.setValue("OK"); form.getChildren().add(command); output = new UIOutput(); output.setValue("</html>"); rootChildren.add(output); } }

A problem with the second approach was that it actually was imported 'accidentally' into the JSF spec proper by adopting Facelets and all implementations incorporating the existing Facelets source. This meant it wasn't properly specified and just happened to work in all those implementations without any guarantees by the backing spec or TCK. Furthermore, its flexibility was rather limited.

In JSF 2.2 the existing "jsfc" approach was therefore revised and re-branded into "pass-through elements". The differences with the new version are as follows:

Using an arbitrary but namespaced attribute instead of the fixed "jsfc" attribute

The value of the special attribute is the normal value for that attribute going to the component instead of the "tag name" of the linked component

There is a default and well-defined mapping of HTML tags to basic JSF components

The mechanism can be easily adopted by third party components

Syntax well aligned with the opposite concept; pass-through attributes

The following shows an example of how the same component tree as used above is specified using the new syntax: Target language format: HTML with special attribute (pass-through element syntax)

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:jsf="http://xmlns.jcp.org/jsf"> <body> <form jsf:id="form"> Welcome, #{loggedInUser.name} <input type="text" jsf:value="#{bean.property}" /> <input type="submit" value="OK" jsf:action="#{bean.doSomething}" /> </form> </body> </html>

Also notice that pass-through elements work exactly the other way around as pass-through attributes.

With pass-through elements, namespaced attributes go to the component, while non-namespaced attributes go directly to the markup.

With pass-through attributes, namespaced attributes go to directly to the markup, while non-namespaced attributes go to the component.

Further reading:

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 2.2 has added 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.

It can be used as follows:

<h:commandButton id="button" value="submit" action="#{someBean.someAction}"> <f:ajax execute="@form" delay="none" /> </h:commandButton>

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:

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

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:

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

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

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

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)

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>

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>

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

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)

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

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

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

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:

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

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

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

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

Assume the following file structure:

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

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

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

(yes only these 3 files, nothing else is needed)

Template from contract implementation 1 Content from template client.

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

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

(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://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/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>

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

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:ui="http://xmlns.jcp.org/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>

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.

Even though resource contracts are documented as being a facility to provide templates to template clients, a somewhat surprising fact is that they serve top-level views as well. To illustrate this, consider the following structure:

/contracts /contract1 test.xhtml test.xhtml

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" > <h:body> Contract file </h:body> </html>

/test.xhtml

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" > <h:body> Root file </h:body> </html>

Besides top level views, includes can also be resolved from a resource contract.

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

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.

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 { // ... }

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:

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

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:test="http://xmlns.jcp.org/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 { // ... }

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

@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 { // ... }

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 has some implicit protection against this when state is saved on the server and no stateless views are used, since a post-back must then contain a valid javax.faces.ViewState hidden parameter. Contrary to earlier versions, this value seems sufficiently random in modern JSF implementations. Do note that stateless views and saving state on the client does not have this implicit protection.

JSF 2.2 introduced an additional/stricter explicit protection against CSRF attacks. Among others client state encryption is now on by default and there's a token parameter for protection of non-postback views, stateless views and views with client side state.

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

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.getDocumentElement().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);

Further reading:

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:

<factory> <flash-factory>com.example.MyFlashFactory</flash-factory> </factory>

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

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

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:

Identification of an individual window: the Client Window Id 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 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

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.

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

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 UIViewRoot s during its lifetime.

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:

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:

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

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)

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>

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

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 )

Further reading:

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.

To illustrate, Mojarra 2.2 now renders the hidden view state field as follows:

Mojarra has retained the com.sun.faces.enableViewStateIdRendering parameter though, so setting this explicitly to false will still remove the id attribute, but with the ID now being unique there should be less need for this.

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.

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

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:

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

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)

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