Jim Driscoll's Blog

Notes on Technology and the Web

Archive for the ‘JSF’ Category

Mixing Ajax and full requests in JSF 2.0

leave a comment »

JSF 2.0 makes ajax pretty easy – but it can’t hide everything from you… It’s tempting to just add a few ajax tags into your page, and not worry too much about interactions – here’s one example of a problem you may run into.

Let’s say you’ve got a page with an input text, and a command button – like this:

   1 <h:form>
   2 <h:inputText value="#{blah.blah}">
   3 </h:inputText>
   4 <h:commandButton/>
   5 </h:form>

Now, we decide to add an ajax tag:

   1 <h:form>
   2 <h:inputText value="#{blah.blah}">
   3 <f:ajax event="blur"/>
   4 </h:inputText>
   5 <h:commandButton/>
   6 </h:form>

Can you spot what’s wrong with this example? When we push the button, we’re also blurring the inputText. That means that the ajax request is sent – but then, almost immediately, that request is canceled as the whole page is reloaded.

Is this a bad thing? For this simple example, not so much. There’s going to be a broken connection – and that can be a grim problem for a large server, especially if you start getting one on each page, for each use.

But the real issue is that you’ve just set up a race condition. Imagine instead you did this:


   1 <h:form>
   2 <h:inputText value="#{blah.blah}">
   3 <f:ajax event="blur" listener="#{bean.somethingthatchangesstate}"/>
   4 </h:inputText>
   5 <h:commandButton/>
   6 </h:form>

Now we’ve got a real problem from that race condition – did the listener execute? Maybe. Maybe is never a good answer in software.

So – what to do?

Probably the best solution is also the simplest:

   1 <h:form>
   2 <h:inputText value="#{blah.blah}">
   3 <f:ajax event="blur" listener="#{bean.somethingthatchangesstate}"/>
   4 </h:inputText>
   5 <h:commandButton>
   6 <f:ajax render="@form">
   7 </h:commandButton>
   8 </h:form>

Switching to ajax for the commandButton will now provide a predictable call sequence.

One more issue: When the two connections are submitted simultaneously, an error alert may be produced. I just updated that error to say: "The Http Transport returned a 0 status code. This is usually the result of mixing ajax and full requests. This is usually undesired, for both performance and data integrity reasons." What happens if you want to do this? Well, the error alert only shows up under two conditions, both of which must be true – the Project Stage must be Development, and there must be no error listener set. So, if you’re really sure you want to mix ajax and full requests, despite what I said above, just set up an error listener for your ajax code – you’ll want to anyway for a production environment.

As always, if you have questions, please ask in the comments.

(This article originally published on my java.net blog on October 2, 2009.)


Written by jamesgdriscoll

February 9, 2010 at 10:32 PM

Posted in ajax, JSF

JSF 2.0 Reminder: Project Stage

leave a comment »

Just a reminder that while you are developing a JSF 2.0 project, you really, really, really should enable the Development Project Stage. Doing this enables better error messages, including in the client side JavaScript, at the cost of some performance.

Enabling this is as simple as putting the below into your web.xml:


When going into production, simply change the project stage to Production, like so:


This will turn off some error messages, and emphasize performance.

(This article originally published on my java.net blog on September 28, 2009.)

Written by jamesgdriscoll

February 9, 2010 at 10:32 PM

Posted in JSF

Ajax tag events and listeners

leave a comment »

Today we’re going to talk about two features of JSF 2.0’s f:ajax tag: the event attribute and the listener attribute.

The use of both of these is really, really simple – so I’ll just briefly cover the basics, and then launch directly into the sample code.

The “event” attribute of the ajax tag indicates which event to use to trigger the ajax request. There are any number of possible events allowed: You can use the standard browser DOM events (like click, change, keyup, etc. You can also use two special event values – action and valueChange. These two special values correspond to the same events that happen on the server side in JSF. On the client side, action is typically mapped to click, while valueChange is mapped to change or click, depending on the component.

The “listener” attribute of an ajax tag is a method that is called on the server side every time the ajax function happens on the client side. For instance, you could use this attribute to specify a server side function to call every time the user pressed a key – Handy, eh?

Anyhow, without further ado, let’s see how this works in a page. We’re going to detect every time the user lifts a key (the keyup event) – when that happens, we’ll run an ajax command which updates a counter, and refreshes an output field.

Here’s the using page:

   1 <?xml version='1.0' encoding='UTF-8' ?> 
   2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3 <html xmlns="http://www.w3.org/1999/xhtml"
   4       xmlns:h="http://java.sun.com/jsf/html"
   5       xmlns:f="http://java.sun.com/jsf/core">
   7     <h:head><title>Ajax Tag Event and Listener Demo</title></h:head>
   8     <h:body>
   9         <h:form id="form">
  10             <br/>
  11             Echo test: <h:outputText id="out" value="#{listenBean.hello}"/>
  12             <br/>
  13             String Length: <h:outputText id="count" value="#{listenBean.length}"/>
  14             <br/>
  15             <h:inputText id="in" value="#{listenBean.hello}" autocomplete="off">
  16                 <f:ajax event="keyup" render="out count eventcount" listener="#{listenBean.update}"/>
  17             </h:inputText>
  18             <br/>
  19             Event count: <h:outputText id="eventcount" value="#{listenBean.eventCount}"/>
  20         </h:form>
  22     </h:body>
  23 </html>

As I said, we tag the inputText (line 15) with an ajax tag (line 16). That ajax tag listens for the keyup event – when such an event occurs, we send an ajax request to the server. That ajax request will run a listener method (listenBean.update), apply the new string value from the inputText (listenBean.hello), and then render out (line 11), count (line 13), and eventcount (line 19).

The bean itself is nothing special: here’s the example below:

   1 import javax.faces.bean.ManagedBean;
   2 import javax.faces.bean.ViewScoped;
   3 import javax.faces.event.AjaxBehaviorEvent;
   5 @ManagedBean(name="listenBean")
   6 @ViewScoped
   7 public class ListenBean {
   9     private String hello = "Hello";
  11     private int length = hello.length();
  13     private int eventCount = 0;
  15     public String getHello() {
  16         return hello;
  17     }
  19     public void setHello(String hello) {
  20         this.hello = hello;
  21     }
  23     public int getLength() {
  24         return length;
  25     }
  27     public int getEventCount() {
  28         return eventCount;
  29     }
  31     public void update(AjaxBehaviorEvent event) {
  32         length = hello.length();
  33         eventCount++;
  34     }
  35 }

So – questions? Ask below.

(This article originally published on my java.net blog on September 26, 2009.)

Written by jamesgdriscoll

February 9, 2010 at 10:29 PM

Posted in ajax, JSF

Bridging to Open Ajax

leave a comment »

The Open Ajax Alliance is a standards organization with the mission of ensuring interoperability within Web based Ajaxified applications. One of their standards relates to intercomponent communication – the ability to subscribe and publish messages which can then be picked up by code written by other authors.

Please note that if you don’t have an interest in Open Ajax, this post may not be especially illuminating – I’ve talked about the addOnEvent function before, even recently.

To write an Open Ajax application, you need to subscribe to events, much like in JSF 2, by registering functions which act as listeners. For instance, suppose we had a field in our page that looked like this:

 <textarea id="statusArea" cols="40" rows="10" readonly="readonly" />

And we wanted to use this textarea to write out certain events that we’d like to track. I could then have this code in a JavaScript file:

   1 var statusUpdate = function statusUpdate(name, data) {
   2     var statusArea = document.getElementById("statusArea");
   3     var text = statusArea.value;
   4     text = text + "Name: "+data.source.id;
   5     if (name === "jsf.event") {
   6         text = text +" Event: "+data.status+"\n";
   7     } else if (name === "jsf.error") {  
   8         text = text + " Error: "+data.status+"\n";
   9     }
  10     statusArea.value = text;
  11 };
  13 OpenAjax.hub.subscribe("jsf.event",statusUpdate);
  14 OpenAjax.hub.subscribe("jsf.error",statusUpdate);

In this case, we’re subscribing to two channels – jsf.event and jsf.error, and calling the statusUpdate function when a message arrives on those channels.

So, where do those messages come from? Unlike JSF, the OpenAjax hub has a publish function, in addition to a subscribe function. By associating that publish function with a call to jsf.ajax.addOnEvent and jsf.ajax.addOnError, we can bridge between the two event systems – like this:

   1 var openajaxbridge = {};
   3 openajaxbridge.eventUpdate = function eventUpdate(data) {
   4     OpenAjax.hub.publish("jsf.event", data);
   5 };
   7 openajaxbridge.errorUpdate = function errorUpdate(data) {
   8     OpenAjax.hub.publish("jsf.error",data);
   9 };
  11 jsf.ajax.addOnEvent(openajaxbridge.eventUpdate);
  12 jsf.ajax.addOnError(openajaxbridge.errorUpdate);

As I said, this is a somewhat specialized topic, but I thought it worth mentioning. The full code of the demo, including putting it into a component, is in Project Mojarra’s source base, under the jsf-demo/OpenAjaxBridge directory.

(This article originally published on my java.net blog on September 3, 2009.)

Written by jamesgdriscoll

February 9, 2010 at 10:08 PM

Posted in ajax, JSF

Busy status indicator with JSF 2

leave a comment »

I’ve had a few requests on how to write a busy status indicator – you know, the little spinning ball that’s there while an Ajax call is active, and which goes away once the request is complete. So, I spent about two hours today, and did just that – including putting it into a component so it’s reusable. As usual, it involved no Java, and only a minimal amount of JavaScript.

First, I needed an animated gif for a spinning image – there were a number at http://mentalized.net/activity-indicators – I just picked one. They’re all in the public domain, and there are other sites which offer similar animated gif spinners.

After that, I tried to imagine what it would look like in the using page. Something like this seemed appropriate:

   1 <html xmlns="http://www.w3.org/1999/xhtml"
   2       xmlns:ui="http://java.sun.com/jsf/facelets"
   3       xmlns:h="http://java.sun.com/jsf/html"
   4       xmlns:f="http://java.sun.com/jsf/core"
   5       xmlns:ez="http://java.sun.com/jsf/composite/busystatus">
   6 <h:head>
   7     <title>Busy Busy</title>
   8 </h:head>
   9 <h:body>
  10     <h:form id="busyForm">
  11         <h:inputText id="in" value="#{string.string}">
  12             <f:ajax render="out"/>
  13         </h:inputText><ez:busystatus id="busy" for="busyForm:in" /><br/>
  14         <h:outputText id="out" value="#{string.string}"/><br/>
  15         <h:commandButton type="button" value="Click Me"/>
  16     </h:form>
  17 </h:body>
  18 </html>

On line 13, you see a component, busystatus, with a single attribute, “for”, which is pointing at the rendered ID of the component I want to monitor. Otherwise, it’s a straightforward JSF Ajax app – Ajaxify the “in” component, write to the the “out” component. I had to use the rendered ID (busyForm:in) rather than the JSF id (in), because there was no easy way to do ID resolution inside the component, but we’ve had to deal with that often enough at this point that the difference shouldn’t be too confusing.

We’ll also have make sure that the Ajax request lasts long enough to visibly trigger the indicator – that’s as simple as adding a Thread.sleep(2000); to the setString method of the bean referenced by #{string}.

With that out of the way, let’s write the component. Here’s the composite component implementation section (the interface section just refers to the “for” attribute, so there’s nothing to see there):

   1 <h:outputScript name="jsf.js" library="javax.faces" target="head"/>
   2 <h:outputScript name="busystatus/busystatus.js" target="head"/>
   3 <script type="text/javascript">
   4     busystatusdemo.init("#{cc.clientId}", "#{cc.attrs.for}");
   5 </script>
   6 <span id="#{cc.clientId}" style="display:none;">
   7    <h:graphicImage id="busyindicator" height="15" width="15" name="busystatus/spinner3-greenie.gif"/>
   8 </span>

Line 1 loads the jsf.js library, if necessary. We’ll need it in the next file for listening to events – note that it’ll get loaded anyway, from any f:ajax tag we use, but it’s good practice to make sure that it’s loaded before we try to reference it. Line 2 will load the JavaScript we’ve written for this component. We could have just put the script inline in the composite component itself, but then we’d bloat the size of the page unnecessarily if we used this component more than once in the page. What works best for performance is going to vary on case by case basis, but since we’re trying to create a generally reusable component, this is probably the best way to do it. Lines 3 thru 5 call the init function for this component, which we’ll use to associate the component ID with the for attribute: this is the same trick we use for almost every Ajax component on this blog, so again, this shouldn’t be surprising.
Lines 6 thru 8 define a span wrapping an image. The span is initially set to be invisible with a style attribute, and we’ll make it visible via JavaScript calls once the ajax request is active. The image itself is loading the spinning animated gif as a resource – and it’s in the same resource library as the component itself.

So, to recap what’s happening in this file: We load the required scripts, run an initialization function, and set up an invisible span holding the image we’ll display later. Now, let’s examine the last file for this component, the busystatus.js file that holds the functions that’ll be doing all the work on the page:

   1 if (!window["busystatusdemo"]) {
   2     var busystatusdemo = {};
   3 }
   4 busystatusdemo.onStatusChange = function onStatusChange(data) {
   5     var status = data.status;
   6     var componentID = busystatusdemo[data.source.id];
   7     if (!componentID) {  // if there's no request to listen for this one component, then leave
   8         return;
   9     }
  10     var element = document.getElementById(componentID);
  11     if (status === "begin") { // turn on busy indicator
  12         element.style.display = "inline";
  13     } else {  // turn off busy indicator, on either "complete" or "success"
  14         element.style.display = "none";
  15     }
  16 };
  18 jsf.ajax.addOnEvent(busystatusdemo.onStatusChange);
  20 busystatusdemo.init =  function init(componentID, forValue) {
  21     busystatusdemo[forValue] = componentID;
  22 };

Three sections here: Lines 1 thru 3 set up the namespace. Lines 20 thru 22 are the initialization function that creates a map between the component and the for attribute. Let’s go over lines 4 thru 18, though, since that’s doing the interesting bit…

On line 18, we’re adding an event listener – after this call, whenever an event occurs, the onStatusChange function will be called with a single parameter. When that function is called, on lines 6 thru 10, we retrieve the id of the component that generated the event, and use it to look up the associated “for” value, and exit the function if there’s no associated “for” value. Then, lines 11 thru 15, we check whether we’re beginning the Ajax call, or ending it. If beginning, we display the gif – if ending, we hide the gif.

So, that’s our very simple busy component. But please note that this isn’t really done. For instance, by revealing and hiding the gif, we’re actually altering the layout of the page – there’s traditionally two different ways to deal with this: you can either swap between the animated gif and a blank, transparent gif of the same size, or use CSS to hardcode in the size of a span, which wraps the component that’s having it’s display set to none. Either would work, and both are really out of scope for this blog – my only goal for this blog was to just show you how to use the event to trigger changes that updated a status indicator.

As usual, you can find the code for this blog in the Project Mojarra codebase, under the jsf-demo/ajax-components directory.

Questions? Please ask in the comments section, and I’ll do my best to answer them.

UPDATE: Ed Burns, in the comments, recommends http://www.ajaxload.info as a great place for all your spinning gif needs.

(This article originally published on my java.net blog on September 2, 2009.)

Written by jamesgdriscoll

February 9, 2010 at 10:07 PM

Posted in ajax, JSF

Inline Scripts with Mojarra

leave a comment »

A few weeks ago, I blogged about ways to execute scripts on the client which you were writing out from the server via Ajax.  By popular demand, the latest build of Mojarra now allows execution of inline scripts.

So, instead of having to either bundle code into an <eval> tag, or using an event to execute it later, you can now simply say something like:

<script type="text/javascript">alert("Hello there");</script>

right inside the rendered html.

You can also say something like:

<script type="text/javascript" src="file.js"></script>

And the script will be loaded as well.

This feature will (probably) be the next revision of the specification, but you should be able to use this feature without fear of compatability issues going forward – the specifcation’s Expert Group has already expressed their approval of including this.

(This article originally published on my java.net blog on September 2, 2009.)

Written by jamesgdriscoll

February 9, 2010 at 10:05 PM

Posted in ajax, JSF

ui:repeat and Ajax

with one comment

A nice feature of Facelets is the ui:repeat tag, which iterates over a supplied list of values to do a full list on your page. One problem: it’ll add an index to the generated id’s, which can make using it with Ajax a bit of a drag. But if you’re just using the f:ajax tag, that index is detected automatically, making ajaxifying the tag relatively easy. Here’s a quick example:

Say you want to make a page that offers three drop down menus with three choices each (it’s a simple example, work with me here). Here’s the data structure, set up as a bean:

   1 package demo;
   3 import java.util.ArrayList;
   4 import java.util.Arrays;
   5 import java.util.List;
   6 import javax.faces.bean.ManagedBean;
   8 @ManagedBean
   9 public class RepeatBean {
  11     private String[] sarray = {"one", "two", "three"};
  12     private String[] sarray2 = {"four", "five", "six"};
  13     private String[] sarray3 = {"seven", "eight", "nine"};
  15     private List<List<String>> llist;
  17     private String[] resultArray = {"two", "four", "nine"};
  19     public RepeatBean() {
  20         List<String> slist = Arrays.asList(sarray);
  21         List<String> slist2 = Arrays.asList(sarray2);
  22         List<String> slist3 = Arrays.asList(sarray3);
  24         llist = new ArrayList<List<String>>();
  25         llist.add(slist);
  26         llist.add(slist2);
  27         llist.add(slist3);
  29     }
  30     public List<List<String>> getLlist() {
  31         return llist;
  32     }
  33     public String[] getResultArray() {
  34         return resultArray;
  35     }
  36     public String getResultArray(int i) {
  37         return resultArray[i];
  38     }
  39     public void setResultArray(int i, String value) {
  40         resultArray[i] = value;
  41     }
  42     public void setResultArray(String[] resultArray) {
  43         this.resultArray = resultArray;
  44     }
  45 }

We create three lists – they’ll be the content of the drop down menus. We then create a list of String lists – llist – we’ll use this as the input for the . We also make a list to hold the results: resultArray.

Now: to use it in a page:

   1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2 <html 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:f="http://java.sun.com/jsf/core"
   6       xmlns:c="http://java.sun.com/jsp/jstl/core">
   7     <h:head>
   8         <title>Repeat Test Demo</title>
   9     </h:head>
  10     <h:body>
  12         <h:form id="repeatForm">
  13             <ui:repeat value="#{repeatBean.llist}" var="list" varStatus="current" id="repeat">
  14                 <h:selectOneMenu value="#{repeatBean.resultArray[current.index]}" id="chooseOne">
  15                     <f:selectItems value="#{list}"/>
  16                     <f:ajax render="outText"/>
  17                 </h:selectOneMenu>
  18                 <h:outputText value="#{repeatBean.resultArray[current.index]}" id="outText"/>
  19                 <br/>
  20             </ui:repeat>
  21         </h:form>
  22     </h:body>
  23 </html>

This ends up generating ids for the outputText field that look like: repeatForm:repeat:2:outText. But because we’re using the f:ajax tag, we only need to specify “outText” – the tag takes care of the work of finding out what the real id is.

Neat, huh? In case you’re not familiar with the ui:repeat tag – you should take a minute to get familiar with it, it’s core Facelets functionality. By using the var value, we’re saying that we want to create a list variable that will contain one of the lists in llist every iteration. By using varStatus and the index property, we’re keeping track of all of the values selected.

Just a simple example of the use of the f:ajax tag in a complex rendered environment. As always, let me know if you have any questions.

(This article originally published on my java.net blog on August 17, 2009.)

Written by jamesgdriscoll

February 9, 2010 at 10:03 PM

Posted in ajax, JSF