Archive for the ‘jsf’ Category

What’s new in JSF 2.3?

6 February 2015

The process of developing JSF 2.3 started late september 2014, which is approximately 1.5 half year after JSF 2.2 was finalized. It currently has an anticipated release date of Q3 2016, which is aligned with the anticipated release date of Java EE 8.

So what will be in JSF 2.3?

The official JSR gives some hints, but is a little vague in what will actually be done. This time around, there is little big upfront planning and because of resources the scope of new features is kept limited.

There have been a few important changes in the organization of the EG as well. While Ed Burns is still the spec lead, there is now a co-spec lead: Manfred Riem. As can be seen from the commit log, Manfred is currently most involved with working in the Mojarra source code. At a personal level, a big change is that both my co-worker Bauke (BalusC) as well as myself are now members of the JSF EG and are actively contributing to JSF.

So instead of merely monitoring the trunk of the reference implementation to see what’s new as I did for JSF 2.2, I’ll now be reporting from the inside 😉

Download

Latest 2.3 snapshot: implementation jar, source jar

Latest JSF 2.3 blog posts

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

New features

CDI


Injection and EL resolving of JSF artifacts (spec issue 1316) (partially)

JSF has traditionally used static entry methods and chaining to let the user obtain the various artifacts that it provides, such as the FacesContext, session map, external context, etc. The following gives a few examples of this:

FacesContext facesContext = FacesContext.getCurrentInstance()
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> cookieMap = FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap();
Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
// etc

Especially the artefacts that have to be obtained by deep chaining can be problematic. Not only makes this the code verbose and hard to read, it can also be unclear to users that the view map has to be obtained via the view root but the cookie map via the external context as shown above.

Furthermore, the pattern makes it hard to override what is returned by the runtime. In JSF it IS possible to influence this by providing/setting a custom FacesContext, but especially for the deeper chained artefacts multiple levels or wrapping are then required, which is not always trivial to implement. The problem there is clearly that the abstraction is at the wrong level; providing an alternative view map requires a custom faces context, which provides a wrapped view root, which then finally provides the view map we wanted to provide.

A more modern approach in Java EE is to inject artefacts in order to obtain them (essentially flattening the lookup) and to provide alternative producers for those when the need to override them arises.

JSF 2.3 will therefore provide default producers for the most important artefacts, which at the moment being:

  • ViewRoot
  • ViewMap (@ViewMap)
  • RequestCookieMap (@RequestCookieMap)
  • SessionMap (@SessionMap)
  • ApplicationMap (@ApplicationMap)
  • FacesContext
  • ExternalContext

The general types, in this case the maps, need an extra qualifier to avoid clashing with other producers. The JSF specific types however don’t need such qualifier since JSF is the sole owner of these types.

Obtaining the JSF artefacts is therefore as easy as can be; one only needs to know the type of the artefact one wants. For example:

@Inject
private ExternalContext context;

For the ones that do need a qualifier, this qualifier has to be looked-up of course, but that’s essentially a flat lookup. For example:

@Inject
@ApplicationMap
private Map<String, Object> applicationMap;

Furthermore, somewhat as a side-effect of Injection in more JSF artifacts, user created instances of the following artefacts are also injectable:

  • Converter
  • Validator
  • Behavior

This list is somewhat different, as we’re not talking about say -the- Converter instance within the current scope, but about a specific named custom converter in the user’s application. E.g.

@Inject
@FacesConverter(value = "myConverter", managed = true)
private Converter myConverter;

Note that this particular injection pattern is possible, but not entirely how things are normally done in CDI.

Commits for this feature have been done between 13/okt/14 and 29/jan/15.


Injection in more JSF artifacts (spec issue 1316) (partially)

In JSF 2.1 very few JSF artifacts were injection targets. In JSF 2.2 injection was made possible in a huge amount of additional artefacts but the very ones where injection actually matters most, converters and validators, were mysteriously left in the cold.

In JSF 2.3 this has now finally been taken care of as the following artefacts have been added to the list of injection targets:

  • javax.faces.convert.Converter
  • javax.faces.validator.Validator
  • javax.faces.component.behavior.Behavior

However, in contrast to the artefacts already on this list these new 3 are not automatically injection targets. They will only become so when a new attribute called “managed” on the corresponding annotations @FacesConverter, @FacesValidator and @Behavior is set to true. Furthermore all these 3 annotations have been upgraded to being CDI qualifiers by adding the @Qualified annotation to their definition.

The existing attributes of @FacesConverter, @FacesValidator and @Behavior have not been modified, meaning they are all *binding*, as is the new attribute “managed”.

What happens behind the scenes now is that when JSF needs a converter it simply asks the CDI bean manager for a bean that implements Converter with a qualifier @FacesValidator that has the “managed” attribute set to true and the value (coverterId) or forClass attribute set to the right value (which is why it’s important that these attributes are all binding).

It then wraps the bean returned by CDI in a delegating converter instance. This wrapper then delegates to the bean returned by CDI. This wrapper can be state-saved, but since the CDI bean is stored in a transient field it won’t save&restore that. Instead, it will only save&restore the converterId or forClass. The restored wrapper will then use the JSF Application instance to ask for a converter with said converterId or forClass (which will go to CDI again, and will do the wrapping again, so we have a double wrapped converter at this point).

In effect the mechanism is essentially quite like the age old workaround of using an EL expression pointing to a managed bean for a converter or validator.

An example of a JSF 2.3 converter in which injection can take place:

@FacesConverter(value = "myConverter", managed = true)
public class MyConverter implements Converter {
 
    @Inject
    private MyService service;
 
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        // Convert string to Object here
    }
 
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        // Convert Object to String here
    }
}

Note that this new style converter must have a constructor as defined by CDI (a no-args one here) and the alternative constructor is not supported here.

Commits for this feature have been done between 14/Jan/15 and 15/jan/15.

Lifecycle


System event published after view rendered (spec issue 1135)

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.2 there are some 20 events defined, e.g. PostAddToViewEvent, PostConstructViewMapEvent, PreValidateEvent, and specifically PreRenderViewEvent.

However, while there’s a PreRenderViewEvent that’s published right before a view is rendered, there’s no event published right after. Such event can be useful for a variety of things, such as per view clean-ups, post rendering view processing, state handling, etc.

For these reasons and simply to be more consistent JSF 2.3 will add a new event called the PostRenderViewEvent, which as its name implies is published immediately after a view is rendered.

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core">
 
    <h:body>
        <f:event type="postRenderView" listener="#{myBean.doPostProcessing}" />
 
     	<!-- Rest of view here -->
    </h:body>
</html>

Commits for this feature have been done on 31/jan/15.

Java API


Support for the Iterable interface in UIData and UIRepeat (spec issue 1103)

From the beginning of JSF, the UIData component (known from e.g. <h:dataTable>) and UIRepeat (known from e.g. <ui:repeat>) only realistically supported the List, native array and JSF specific DataModel as input for its value binding. This meant other collection types had to be expressed as one of these types.

In JSF 2.2 UIData was extended to support Collection as well, but UIRepeat was mysteriously left out (which is one reason why UIRepeat should really share common functionality with UIData; it happens much more often that both should be updated but only one of them is)

The thing is that while Collection support is nice, it’s actually just as easy to support Iterable. It’s perhaps a small oversight that this was not supported right from the beginning, but in JSF 2.3 this will finally be addressed.

Just as with the Collection support in 2.2, Iterable will be added to the bottom of the list of types being checked, so for Iterables that are also a List or Collection (in case of UIData), the existing code will take precedence.

The following are now the supported types for UIData:

  • 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
  • java.lang.Iterable new!
  • java.lang.Object (becomes ScalarDataModel)

And the following are the supported types for UIRepeat:

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

Note that both Result and Collection are missing for UIRepeat. The latter will be handled by Iterable, since it’s the base class of Collection. Result is actually missing, likely because its JSP specific and UIRepeat was designed specifically for Facelets).

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


Support for the Map interface in UIData and UIRepeat (spec issue 1364)

Besides support for the Iterable interface in UIData and UIRepeat, JSF 2.3 will also add support for maps. The way this is done is closely aligned with how JSTL has supported maps for many years:

Existing JSTL based looping through a map

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>

New JSF 2.3 based looping through a map using ui:repeat

<ui:repeat var="entry" value="#{myMap}">
    Key: #{entry.key}
    Value: #{entry.value}
</ui:repeat>

New JSF 2.3 based looping through a map using h:dataTable

<h:dataTable var="entry" value="#{myMap}">
    <h:column>#{entry.key}</h:column>
    <h:column>#{entry.value}</h:column>
</h:dataTable>

Including the Iterable support from the previous feature and the Map support discussed here, the following are now the supported types for UIData:

  • 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
  • java.lang.Iterable new!
  • java.util.Map new!
  • java.lang.Object (becomes ScalarDataModel)

And the following are the supported types for UIRepeat:

  • null (becomes empty list)
  • javax.faces.model.DataModel
  • java.util.List
  • java.lang.Object[]
  • java.sql.ResultSet
  • java.lang.Iterable new!
  • java.util.Map new!
  • java.lang.Object (becomes ScalarDataModel)

Commits for this feature have been done on 18/mar/15.

Configuration


Facelets default to non-hot reload in production (spec issue 936)

JSF has the ability to cache Facelets. Caching here means that the result of the XML parsing and compilation step is kept in memory, e.g. Facelets will not read the XML from disk at every request and will not reparse that XML either. (it will however still do the composition of includes and templates at every request)

While the default is not specified, the RI (Mojarra) uses a default of 2 seconds before it looks on disk again if the source file has changed or not. There is a setting to control this default, namely the javax.faces.FACELETS_REFRESH_PERIOD context parameter in web.xml. For example, the following sets a timeout of 10 seconds:

<context-param>
    <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
    <param-value>10</param-value> <!-- Cache for 10 seconds -->
</context-param>

There are two special values; -1 means no refresh (cache indefinitely), while 0 means no caching at all (always hot reload).

For production usage there really is only 1 sensible value, and that’s -1, as the Facelets source files will of course not change during production.

JSF 2.0 introduced a setting to indicate the stage its in, which includes the Production stage.

JSF 2.3 now finally adds one and one together and defines that when the project stage is Production (which incidentally is the default stage) the Facelets refresh period is -1 (no refresh).

Commits for this feature have been done on 25/feb/15.


That’s it for now! I’ll periodically update this page to cover the latest JSF 2.3 developments. In the short term this may be a dedicated folder to store views and a generic parameter adding to the Converter and Validator interfaces, but this is all preliminary.

Arjan Tijms

Serving multiple images from database as a CSS sprite

31 July 2013

Introduction

In the first public beta version of ZEEF which was somewhat thrown together (first get the minimum working using standard techniques, then review, refactor and improve it), all favicons were served individually. Although they were set to be agressively cached (1 year, whereby a reload is when necessary forced by the timestamp-in-query-string trick with the last-modified timestamp of the link), this resulted in case of an empty cache in a ridiculous amount of HTTP requests on a subject page with relatively a lot of links, such as Curaçao by Bauke Scholtz:

Yes, 209 image requests of which 10 are not for favicons, which nets as 199 favicon requests. Yes, that much links are currently on the Curaçao subject. The average modern webbrowser has only 6~8 simultaneous connections available on a specific domain. That’s thus a huge queue. You can see it in the screenshot, it took on an empty cache nearly 5 seconds to get them all (on a primed cache, it’s less than 1 second).

If you look closer, you’ll see that there’s another problem with this approach: links which doesn’t have a favicon re-requests the very same default favicon again and again with a different last-modified timestamp of the link itself, ending up in copies of exactly same image in the browser cache. Also, links from the same domain which share the same favicon, have their favicons duplicated this way. In spite of the agressive cache, this was simply too inefficient.

Converting images to common format and size

The most straightforward solution would be to serve all those favicons as a single CSS sprite and make use of CSS background-position to reference the right favicon in the sprite. This however requires that all favicons are first parsed and converted to a common format and size which allows easy manipulation by standard Java 2D API (ImageIO and friends) and easy generation of the CSS sprite image. PNG was chosen as format as that’s the most efficient and lossless format. 16×16 was chosen as default size.

As first step, a favicon parser was created which verifies and parses the scraped favicon file and saves every found image as PNG (the ICO format can store multiple images, usually each with a different dimension, e.g. 16×16, 32×32, 64×64, etc). For this, Image4J (a mavenized fork with bugfix) has been of a great help. The original Image4J had only a minor bug, it ran in an infinite loop on favicons with broken metadata, such as this one. This was fixed by vijedi/image4j. However, when an ICO file contained multiple images, this fix discarded all images, instead of only the broken one. So, another bugfix was done on top of that (which by the way just leniently returned the “broken” image — in fact, only the metadata was broken, not the image content itself). Every single favicon will now be parsed by ICODecoder and BMPDecoder of Image4J and then ImageIO#read() of standard Java SE API in this sequence. Whoever returned the first non-null BufferedImage(s) without exceptions, this will be used. This step also made us able to completely bypass the content-type check which we initially had, because we discovered that a lot of websites were doing a bad job in this, some favicons were even served as text/html which caused false negatives.

As second step, if the parsing of a favicon resulted in at least one BufferedImage, but no one was in 16×16 dimension, then it will be created based on the firstnext dimension which is resized back to 16×16 with help of thebuzzmedia/imgscalr which yielded high quality resizings.

Finally all formats are converted to PNG and saved in the DB (and cached in the local disk file system).

Serving images as CSS sprite

For this a simple servlet was been used which does basically ultimately the following in doGet() (error/cache checking omitted for simplicity):

Long pageId = Long.valueOf(request.getPathInfo().substring(1));
Page page = pageService.getById(pageId);
long lastModified = page.getLastModified();
byte[] content = faviconService.getSpriteById(pageId, lastModified);
 
if (content != null) { // Found same version in disk file system cache.
    response.getOutputStream().write(content);
    return;
}
 
Set<Long> faviconIds = new TreeSet<>();
faviconIds.add(0L); // Default favicon, appears as 1st image of sprite.
faviconIds.addAll(page.getFaviconIds());
 
int width = Favicon.DEFAULT_SIZE; // 16px.
int height = width * faviconIds.size();
 
BufferedImage sprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = sprite.createGraphics();
graphics.setBackground(new Color(0xff, 0xff, 0xff, 0)); // Transparent.
graphics.fillRect(0, 0, width, height);
 
int i = 0;
 
for (Long faviconId : faviconIds) {
    Favicon favicon = faviconService.getById(faviconId); // Loads from disk file system cache.
    byte[] content = favicon.getContent();
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(content));
    graphics.drawImage(image, 0, width * i++, null);
}
 
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(sprite, "png", output);
content = output.toByteArray();
faviconService.saveSprite(pageId, lastModified, content); // Store in disk file system cache.
response.getOutputStream().write(content);

To see it in action, you can get all favicons of the page Curaçao by Bauke Scholtz (which has page ID 18) as CSS sprite on the following URL: https://zeef.com/favicons/page/18.

Serving the CSS file containing sprite-image-specific selectors

In order to present the CSS sprite images at the right places, we should also have a simple servlet which generates the desired CSS stylesheet file containing sprite-image-specific selectors with the right background-position. The servlet should basically ultimately do the following in doGet() (error/cache checking omitted to keep it simple):

Long pageId = Long.valueOf(request.getPathInfo().substring(1));
Page page = pageService.getById(pageId);
 
Set<Long> faviconIds = new TreeSet<>();
faviconIds.add(0L); // Default favicon, appears as 1st image of sprite.
faviconIds.addAll(page.getFaviconIds());
 
long lastModified = page.getLastModified().getTime();
int height = Favicon.DEFAULT_SIZE; // 16px.
 
PrintWriter writer = response.getWriter();
writer.printf("[class^='favicon-']{background-image:url('../page/%d?%d')!important}", 
    pageId, lastModified);
int i = 0;
 
for (Long faviconId : faviconIds) {
    writer.printf(".favicon-%s{background-position:0 -%spx}", faviconId, height * i++);
}

To see it in action, you can get the CSS file of the page Curaçao by Bauke Scholtz (which has page ID 18) on the following URL: https://zeef.com/favicons/css/18.

Note that the background-image URL has the page’s last modified timestamp in the query string which should force a browser reload of the sprite whenever a link has been added/removed in the page. The CSS file itself has also such a query string as you can see in HTML source code of the ZEEF page, which is basically generated as follows:

<link id="favicons" rel="stylesheet" 
    href="//zeef.com/favicons/css/#{zeef.page.id}?#{zeef.page.lastModified.time}" />

Also note that the !important is there to overrule the default favicon for the case the serving of the CSS sprite failed somehow. The default favicon is specified in general layout CSS file layout.css as follows:

#blocks .link.block li .favicon,
#blocks .link.block li [class^='favicon-'] {
    position: absolute;
    left: -7px;
    top: 4px;
    width: 16px;
    height: 16px;
}
 
#blocks .link.block li [class^='favicon-'] {
    background-image: url("#{resource['zeef:images/default_favicon.png']}");
}

Referencing images in HTML

It’s rather simple, the links were just generated in a loop whereby the favicon image is represented via a plain HTML <span> element basically as follows:

<a id="link_#{linkPosition.id}" href="#{link.targetURL}" title="#{link.defaultTitle}">
    <span class="favicon-#{link.faviconId}" />
    <span class="text">#{linkPosition.displayTitle}</span>
</a>

The HTTP requests on image files have been reduced from 209 to 12 (note that 10 non-favicon requests have increased to 11 non-favicon requests due to changes in social buttons, but that’s not further related to the matter):

It took on an empty cache on average only half a second to download the CSS file and another half a second to download the CSS sprite. Per saldo, that’s thus 5 times faster with 197 connections less! On a primed cache it’s even not requested at all. Noted should be that I’m here behind a relatively slow network and that the current ZEEF production server on a 3rd party host isn’t using “state of the art” hardware yet. The hardware will be handpicked later on once we grow.

Reloading CSS sprite by JavaScript whenever necessary

When you’re logged in as page owner, you can edit the page by adding/removing/drag’n’drop links and blocks. This all takes place by ajax without a full page reload. Whenever necessary, the CSS sprite can during ajax oncomplete be forced to be reloaded by the following script which references the <link id="favicons">:

function reloadFavicons() {
    var $favicons = $("#favicons");
    $favicons.attr("href", $favicons.attr("href").replace(/\?.*/, "?" + new Date().getTime()));
}

Basically, it just updates the timestamp in the query string of the <link href> which in turn forces the webbrowser to request it straight from the server instead of from the cache.

Note that in case of newly added links which do not exist in the system yet, favicons are resolved asynchronously in the background and pushed back via Server-Sent Events. In this case, the new favicon is still downloaded individually and explicitly set as CSS background image. You can find it in the global-push.js file:

function updateLink(data) {
    var $link = $("#link_" + data.id);
    $link.attr("title", data.title);
    $link.find(".text").text(data.text);
    $link.find("[class^='favicon-']").attr("class", "favicon")
        .css("background-image", "url(/favicons/link/" + data.icon + "?" + new Date().getTime() + ")");
    highlight($link);
}

But once the HTML DOM representation of the link or block is later ajax-updated after an edit or drag’n’drop, then it will re-reference the CSS sprite again.

The individual favicon request is also done in “Edit link” dialog. The servlet code for that is not exciting, but for the case you’re interested, the URL is like https://zeef.com/favicons/link/354 and all the servlet basically does is (error/cache checking omitted for brevity):

Long linkId = Long.valueOf(request.getPathInfo().substring(1));
Link link = linkService.getById(linkId);
Favicon favicon = faviconService.getById(link.getFaviconId());
byte[] content = favicon.getContent();
response.getWriter().write(content);

Note that individual favicons are not downloaded by their own ID, but instead by the link ID, because a link doesn’t necessarily have any favicon. This way the default favicon can easily be returned.


This article is also posted on balusc.blogspot.com.

What’s new in JSF 2.2?

1 September 2012

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

Originally it had an anticipated release of the final draft of the spec in Q4 2011 (see Jsf 2 2-bof, slide 3 and JSR 344: JavaServer Faces 2.2). This date slipped, and was first delayed to the first half of 2012 and then finally a date was set for the end of 2012, but that too proved to be insufficient. Following the delay of Java EE 7 itself, JSF 2.2 was then scheduled for 27/mar/2013.

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

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

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

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

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

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

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

One source worth looking at was the actual trunk of the reference implementation and its associated implementation JIRA as well as that of the public specification JIRA.

In this post I’ve highlighted some items from that activity that I found interesting. The full list of all changes and the exact description of them can be found in the official JSF 2.2 specification.

Download

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

Latest JSF 2.2 blog posts

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

New features

Cancelled

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

GET Support


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

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

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

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

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

A very simple example:

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

Further reading:

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

Navigation


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

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

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

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

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

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

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

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

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

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

A flow scoped bean looks as follows:

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

The value someFlowName references the name of the flow this bean will back. Flows itself are defined via 3 conventions:

  1. A folder in the web root with the name of the flow (e.g. /someFlowName)
  2. An entry view with as base name the name of the flow inside the above mentioned folder (e.g. /someFlowName/someFlowName.xhtml)
  3. A flow configuration file with as name the flow name again ending on “-flow.xml” and also put in the above mentioned folder (e.g. /someFlowName/someFlowName-flow.xml)

A minimal flow configuration has to define 1 exit condition using the following syntax:

/someFlowName/someFlowName-flow.xml:

<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 id="someFlowName">
 
    <flow-return id="someReturnName">
      <from-outcome>#{someBean.someReturn}</from-outcome>
    </flow-return>
 
  </flow-definition>
 
</faces-config>

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

Intermediate nodes (aka member views) have to declare that they are part of the flow using the <<view> element. The following shows an example of an intermediate node:

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

(note that the full view path and name is given, so “/someFlowName” is repeated all the time. An id also *must* be provided and is not defaulted to anything)

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

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

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

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

(remember that someReturnName was defined as the id of the <flow-return> return element)

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>

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

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

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

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

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

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

Alternatively a TagHandler can be used as follows:

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

Note that this exactly mimics normal attributes vs f:attribute

Setting multiple attributes looks as follows:

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

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

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

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

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

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

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

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

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

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


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:

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

While the predominant view of JSF seems to be that it’s all about the first item, JSF has in fact, more or less, supported all of the three options listed above.

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>

Target language format: HTML with special attribute

<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<UIComponent> rootChildren = root.getChildren();
 
        UIOutput output = new UIOutput();
        output.setValue("&lt;html xmlns="http://www.w3.org/1999/xhtml">");                
        rootChildren.add(output);
 
        HtmlBody body = new HtmlBody();
        rootChildren.add(body);
 
        HtmlForm form = new HtmlForm();
        body.getChildren().add(form);
 
        ValueExpression messageProperty = expressionFactory.createValueExpression(elContext, "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("&lt;/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>

One thing to notice here is that there’s no direct replacement for the <span> tag mapping to h:outputText. In the example used above directly using an EL expression in the template suffices, but if we needed to turn off the automatic escaping that such EL expression does or any kind of conversion using a converter, we would have had to find an alternative.

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:

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

AJAX


Queue control for AJAX requests (spec issue 1050)

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

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

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

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

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


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

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

An AJAX variant is even more difficult, not in the least since it’s not directly supported in HTML. The so-called XHR level 2 (aka XMLHttpRequest 2) does support this, but at the moment it’s still a working draft and only the very latest versions of the major browsers support it. Therefor it’s not yet a viable option to use in a specification.

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

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

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

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

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

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

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

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

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

Further reading:

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

State


Stateless views (spec issue 1055) Big Ticket Feature

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Example of this feature:

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

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

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

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

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

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

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

Resources


ResourceResolver unified with ResourceHandler (spec issue 809)

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

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

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

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

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

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

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

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

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

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

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

public ViewResource createViewResource(FacesContext context, String resourceName)

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

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

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

In the reference implementation backwards compatibility was initially only partially enabled.

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

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

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

ViewHandler#viewExists -> ResourceHandler#createViewResource

In later versions of Mojarra this was luckily corrected, and the ResourceResolver is consulted in both scenarios.

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

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

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

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

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


Resource Library Contracts (spec issue 763) Big Ticket Feature

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Assume the following file structure:

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

With the following file contents:

/contracts/contract1/template.xhtml

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

contract-client.xhtml

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

When packing these 2 files in a ROOT.war along with an (empty) WEB-INF/faces-config.xml (yes only these 3 files, nothing else is needed) and deploying it, requesting localhost:8080/contract-client.jsf will yield the following result:

Template from contract implementation 1 
Content from template client.

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

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

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

Assume the following file structure:

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

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

/contracts/contract2/template.xhtml

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

With the file definitions as follows:

/contracts/contract1/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>

and

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

After deploying this to a Java EE server and requesting http://localhost:8080/test.jsf Contract file will be rendered instead of Root file. In order to switch between contracts when requesting top level views the <f:view> tag can of course not be used to switch, since the view must be chosen before seeing the view. In that case the switcher can use something like a custom VDL though, which is responsible for tracking the current contract.

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

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

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


CDI compatible @ViewScoped (spec issue 1087)

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

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

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

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

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

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

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

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

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

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

The exact Javadoc that said this was:

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

(emphasis mine)

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

Example in code:

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

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


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

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

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

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

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

For instance:

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

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

page.xhtml

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

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


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

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

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

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

@FaceletsResourceResolver.

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

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


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

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

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

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

If needed the name can be specified explicitly:

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

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

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

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

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

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

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

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

Security / Type-safety


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

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

JSF 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

 

com/example/MyInitializer.java

public class MyInitializer extends ApplicationConfigurationPopulator {
 
    public void populateApplicationConfiguration(Document document) {
        String ns = document.getDocumentElement().getNamespaceURI();
 
        Element applicationEl = document.createElementNS(ns, "application");
        Element viewHandlerEl = document.createElementNS(ns, "view-handler");
 
        viewHandlerEl.appendChild(
            document.createTextNode(MyViewHandler.class.name())
        );
 
        applicationEl.appendChild(viewHandlerEl);
        document.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:

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

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

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


    Instantiating (composite) component in Java via tag name (spec issue 599)

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

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

    JSF 2.2 now provides an explicit API for this, which as a side-effect can also be used to instantiate regular components by their namespace/tag name. The following shows an example:

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

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

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

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

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


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

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

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

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

    The following are now the supported types:

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

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

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


    Many additional wrapper classes

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

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

    Until now there weren’t wrapper classes for:

    • Lifecycle
    • ActionListener
    • Renderer
    • NavigationCase
    • NavigationHandler

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

    • LifecycleWrapper
    • ActionListenerWrapper
    • RendererWrapper
    • NavigationCaseWrapper
    • NavigationHandlerWrapper

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

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

    Lifecycle


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    The JavaDoc for ClientWindow mentions the following:

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

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

    See also these resources:

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


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

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

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

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

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

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


    System events for The Flash (spec issue 766)

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

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

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

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

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


    Publish PostRestoreStateEvent (spec issue 1061)

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

    public static boolean hasMetadata(UIViewRoot root)

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

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


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

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

    Consider the following use case:

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

    So far so good.

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

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

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

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

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

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

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

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

    Example:

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

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

    Example:

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

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

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

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

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

    Further reading:

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

    XML configuration


    Case insensitivity for state saving method (spec issue 1010)

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

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


    Standardized server state serialization (spec issue 1127)

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

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

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

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

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

    Example of setting server state to use serialization:

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

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


    Configurable resource directory (spec issue 996)

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

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

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

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

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

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

    Further reading:

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

    Standards compliance


    Unique ids and fixed name attribute for view state field (spec issue 220)

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

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

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

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

    Therefor from JSF 2.2 on only the name attribute is mandated to have the fixed name. JSF 2.2 compatible libraries wanting to do something with the viewstate now have to work with a name-spaced Id (like other ‘normal’ elements in the markup rendered by JSF), or do lookups based on the name name attribute if they want to continue using the fixed name.

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

    <input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:0" value="-1290429441786177155:-2938929670926778824" autocomplete="off" />

    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.

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

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

    To assist with managing this context, JSF 2.2 would have introduced a ComponentModificationManager that could have been obtained via a call to FacesContext#getComponentModificationManager

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

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

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

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

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


    Component modification management (spec issue 763)

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

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

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


    FaceletFactory in the standard API (spec issue 611)

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

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

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

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


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

    Arjan Tijms

    Sample CRUD application with JSF and RichFaces

    30 March 2012

    During my thesis project I will be using JavaServer Faces. Therefore it is important I get familiar with the framework. To get familiar I made a small CRUD (Create Read Update Delete) application. It is a simple application that makes it possible to keep track of users. It consists of a user list, a page to add/edit users and a page to delete a user.

    The code

    The research project will focus on when it is beneficial to use client-side scripting instead of/complementary to server side programming. To get up to speed a small CRUD application has been made without the use of client-side scripting and the same CRUD application was adapted to use client-side scripting by using RichFaces. The client-side scripting was added to the editing form to allow validating the form, without the need of making requests to the server.

    The structure of the source project is as follows:

    • backing
      • Index.java – Backing for index.xhtml
      • UserDelete.java – Backing for UserDelete.xhtml
      • UserEdit.java – Backing for UserEdit.xhtml
    • constraints
      • Email.java –  Validation annotation for fields. Fields with this annotation are validated to be a proper email address.
      • EmailConstraintValidator.java – Performs the validation for email addresses.
    • ejb
      • UserDAO.java – Data Access Object for users.
    • entities
      • User.java – Bean object for a user. The fields of this object are annotated with validators.
      • UserConvertor.java – Converts a userId to a user.
    • util
      • Messages.java – Utility object that helps with sending messages between pages.

    The following JSF pages are in the project:

    • index.xhtml – Page with a list with all users
    • user_delete.xhtml – Page used to confirm whether a user should be validated
    • user_edit.xhtml – Page used for adding and editing users

    While creating this application, I tried as much as possible to adhere to best practices. For examples, to go from the master (list) view to the detail (edit) view a GET request is used with the user id as parameter. The user is modified via POST and there’s a redirect and GET back to the master view (PRG pattern).

    Both applications make use of Enterprise Java Beans, Bean Validation and Java Persistence API. EJB is used to inject persistence in the managed beans. Bean validation is used to ensure the data is consistent with the business rules.

    In the RichFaces version user_edit.xhtml is updated to have client-side validations. Only the email address cannot be validated on the client. For that field is Ajax used.

    The code of the project has been uploaded to Google Code so it can viewed by everyone. The code without the use of client-side scripting is put in the default branch and the code with client-side scripting is put in the RichFaces branch.

    Demo

    The compiled applications have been uploaded to OpenShift. It makes showing your work to the public very easy. This is a free cloud platform which runs a JBoss server. The projects can be directly uploaded from Eclipse to the OpenShift server. The live demo can be viewed here.

    To upload your project yourself to OpenShift it is first required to make an account at OpenShift. Then register your public key at OpenShift. When you have the OpenShift plug-in installed in Eclipse you can add the OpenShift server to the server view in Eclipse. From there you can get the default project from OpenShift. This project is only used to send the war files to server, not to hold the code. By adding the JSF project to the OpenShift server it automatically places the war file in the OpenShift project during a publish. By pushing the OpenShift project to the server using GIT, the application is put in the cloud and is ready to use. The detailed process to upload to OpenShift from Eclipse is available here.

    So wrapping up, I’ve made a small project to get familiar with the code, I have uploaded the code to Google Code and I’ve put the application OpenShift.

    Mark van der Tol

    Passing action methods into Facelets tags

    6 January 2012

    The problem

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

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

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

    Finding a solution

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

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

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

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

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

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

    1. // case A: ValueExpression exists, getValue which must
    2. // be a MethodExpression
    3. VariableMapper varMapper = ctx.getVariableMapper();
    4. ValueExpression ve = null;
    5. if (varMapper != null) {
    6.     ve = varMapper.resolveVariable(this.image);
    7.     if (ve != null) {
    8.         obj = ve.getValue(ctx);
    9.     }
    10. }
    11. // (case B omitted)
    12. if (obj instanceof MethodExpression) {
    13.     return (MethodExpression) obj;
    14. }

    Code

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

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

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

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

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

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

    Using the tag handler

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

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

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

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

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

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

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

    Any other alternatives?

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

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

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

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

    An implementation of this is readily available in the new OmniFaces library, from where you can find the documentation and the full source code. There’s also a live demo available.

    Arjan Tijms

    Automatic to-Object conversion in JSF selectOneMenu & Co.

    21 December 2011

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

    A well established pattern in JSF is the following:

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

    With userConverter defined as something like:

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

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

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

    But is using a DAO here really needed?

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

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

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

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

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

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

    The base class is implemented as follows:

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

    And the SelectItemsUtils class:

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

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

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

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

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

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

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

    An implementation of this is readily available in the new OmniFaces library, from where you can find the documentation and the full source code. There’s also a live demo available.

    Arjan Tijms

    Single class pure Java JSF application

    18 September 2011

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

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

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

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

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

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

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

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

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

    Arjan Tijms

    Authoring JSF pages in pure Java

    12 September 2011

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

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

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

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

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

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

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

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

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

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

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

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

    This will be rendered as follows:

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

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

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

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

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

    This page is rather simple and is rendered as:

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

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

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

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

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

    Arjan Tijms

    Simple Java based JSF custom component

    4 September 2011

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

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

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

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

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

    components/CustomComponent.java

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

    Unfortunately, a registration in an XML file is still required in JSF 2.1 to use this as a tag (note, that in JSF 2.2 this isn’t required anymore):

    META-INF/my.taglib.xml

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

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

    page.xhtml

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

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

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

    Arjan Tijms

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

    21 August 2011

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

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

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

    The following shows the code of the 3 files involved:

    page.xhtml

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:jsf="http://xmlns.jcp.org/jsf">
        <body>
            #{backingBean.hello}
     
            <form jsf:id="form">
                <input type="text" jsf:value="#{backingBean.name}" />
                <input type="submit" value="Say Hello" jsf:action="#{backingBean.sayHello}" /> 
            </form>
        </body>
    </html>

    BackingBean.java

    import javax.ejb.EJB;
    import javax.faces.bean.ManagedBean;
     
    @ManagedBean
    public class BackingBean {
     
        String name;
        String hello;
     
        @EJB
        BusinessBean businessBean;
     
        public void sayHello() {
            hello = businessBean.generateHello(name);
        }
     
        public String getName() {
            return name;
        }
     
        public void setName(String name) {
            this.name = name;
        }
     
        public String getHello() {
            return hello;
        }
    }

    BusinessBean.java

    import javax.ejb.Stateless;
     
    @Stateless
    public class BusinessBean {
     
        public String generateHello(String name) {
            return String.format("Hello, %s!", name);
        }    
    }

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

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

    A simple exploded Java EE application deployment to GlassFish

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

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

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

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

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

    Arjan Tijms

    css.php best counter