Skip navigation
1 2 Previous Next


20 posts

Recently I had the privilege of writing an article for Java Tech Journalabout using HTML5 Server Sent Events in a JSF 2 User Interface.  I've made that article available here.

Recently, we've enabled a "view" to simplify the monitoring of JSF automated tests through the Hudson framework. The introduction of clustering support in GlassFish has expanded our JSF automated test suite coverage. The URL for the view is:

On a side note - and redirect to and respectively.

One of the features that had been lacking in JSF has been the ability to use the JSR 330 @Inject annotation for injecting object instances into JSF managed beans.  The feature now has been enabled in GlassFish 3.1 - starting with the latest July 22 nightly builds, or a current source build.  So now, you should be able to use it in a JSF managed bean as follows:


import javax.inject.Inject;



public class UserNumberBean implements Serializable {

    private Count count;


    public String getCount() {
        if (null !=count) {
            return count.getCount();
        } else {
            return "";






My slides for "Exploring HTML5 With JavaServer Faces 2.0" slides are available at Slideshare: Available at:

The ongoing HTML5 specification offers many features to promote a "rich" web user experience.  If you've worked wth HTML5, you know that some features are available in some browsers and not available in others.  Here's a handy tool to tell you the HTML5 features that are available in your favorite browser.  All you need to do is fire up a browser and visit: .  With this, you'll see a nice breakdown of the features that are available in the current browser version.  It will also tell you, the strengh of support for each feature.  For example, for the current version of Firefox I'm using (3.6.3), it says it has a total score of 101 out of 160.  Here's a breakdown for each of the current browsers I'm using:

Firefox 3.6.3101/160
Safari 4.0.3115/160
Opera 10.10  38/160
Chrome 5.0.375.55 beta142/160

Of course if you really like an HTML5 feaure that is not available in your favorite browser, you can always check the "development" versions for the browser - as HTML5 support is still a work in progress. 

I've had questions about how to inject Web Beans into servlets and whether that is supported.  In this entry I'll outline a method of accomplishing just that.
This is a simple login application that communicates to a servlet using Ajax calls from a JSP view.  I'm not going to focus on the view or the protocol (Ajax) that  is used to communicate with the servlet.  If you are interested in that, you can check out the source (instructions at the end of this post).  I'm going to focus on the servlet code and the supporting classes for the application.  The application just prompts for a user name / pasword, and pressing the submit button sends those values to a servlet.  First, let's take a look at some of the supporting code for the application:

Listing 1: Login Credentials

  1. package webbeansservlet;
  3. import javax.enterprise.context.RequestScoped;
  4. import javax.enterprise.inject.Default;
  5. import javax.inject.Named;
  7. /**
  8.  * This is just a simple container class Web Bean for the username
  9.  *  and password entry values.
  10.  */
  11. @Named
  12. @RequestScoped
  13. @Default
  14. public class Credentials {
  15.     private String username = null;
  16.     private String password = null;
  17.     public String getUsername() {
  18.         return username;
  19.     }
  20.     public void setUsername(String username) {
  21.         this.username = username;
  22.     }
  23.     public String getPassword() {
  24.         return password;
  25.     }
  26.     public void setPassword(String password) {
  27.         this.password = password;
  28.     }
  29. }


  • Line 11: The name of this Web Bean will be credentials since we don't supply an argument to the Named annotation.
  • Line 12: For the purposes of this simple application this Web Bean scope will be for the current request.
  • Line 13: Specifies the default qualifier type for this Web Bean.  Note that you should not have to specify this if it's the only qualifier type being used.  In future implementations of Web Beans this should be fixed.

Listing 2: Login

  1. package webbeansservlet;
  3. import;
  4. import javax.enterprise.context.SessionScoped;
  5. import javax.enterprise.inject.Default;
  6. import javax.inject.Inject;
  7. import javax.inject.Named;
  9. /**
  10.  * A simple Web Bean that performs a login operation with user's
  11.  * credentials.
  12.  */
  13. @Named
  14. @SessionScoped
  15. @Default
  16. public class Login implements Serializable {
  18.     @Inject Credentials credentials;
  20.     private boolean loggedIn = false;
  22.     /**
  23.      * This is where you could potentially access a database.
  24.      */
  25.     public void login() {
  26.         if ((credentials.getUsername() != null &&
  27.            credentials.getUsername().trim().length() > 0) &&
  28.             (credentials.getPassword() != null &&
  29.            credentials.getPassword().trim().length() > 0)) {
  30.             loggedIn = true;
  31.         }
  32.     }
  34.     public boolean isLoggedIn() {
  35.         return loggedIn;
  36.     }
  38. }
  • Line 13: The name of this Web Bean will be login
  • Line 14: This Web Bean will exist for the session
  • Line 15: Specifies the default qualifier type for this Web Bean.
  • Line 18: We're injecting an instance of Credentials so we can check the validity of the user name and password entries

Listing 3: Login Servlet

  1. package webbeansservlet;
  2. import;
  3. import;
  4. import javax.enterprise.inject.spi.BeanManager;
  5. import javax.inject.Inject;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.annotation.WebServlet;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  12. /**
  13.  * This Servlet class demonstrates Web Beans injection.
  14.  */
  15. @WebServlet(name="LoginServlet", urlPatterns={"/LoginServlet"})
  16. public class LoginServlet extends HttpServlet {
  18.     // Inject Web Beans Bean Manager.
  19.     @Inject BeanManager m;
  21.     // Inject The Credentials Web Bean.
  22.     @Inject Credentials credentials;
  24.     // Inject the Login Web Bean.
  25.     @Inject Login login;
  27.     /**
  28.      * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
  29.      * @param request servlet request
  30.      * @param response servlet response
  31.      * @throws ServletException if a servlet-specific error occurs
  32.      * @throws IOException if an I/O error occurs
  33.      */
  34.     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  35.         throws ServletException, IOException {
  36.         response.setContentType("text/html;charset=UTF-8");
  37.         PrintWriter out = response.getWriter();
  38.         credentials.setUsername(request.getParameter("username"));
  39.         credentials.setPassword(request.getParameter("password"));
  40.         login.login();
  41.         try {
  42.             if (login.isLoggedIn()) {
  43.                 out.println("Successfully Logged In As: " + credentials.getUsername());
  44.             } else {
  45.                 out.println("Login Failed: Check username and/or password.");
  46.             }
  47.         } finally {
  48.             out.close();
  49.         }
  50.     }
  51.    .......
  52. }
  • Line 15: New for Servlet 3.0 - eliminates servlet entry in web.xml! Not relevant to this example, but worth mentioning.
  • Line 19: The Web Beans Bean Manager can also be injected.  The Bean Manager api provides some useful methods for interrogating portions of a Web Beans application.
  • Line 22: The Credentials Web Bean is injected making it available to the servlet.
  • Line 38: Now we can access the Credentials Web Bean.
  • Line 40: We can also use the injected Login Web Bean instance.

This is just one example of Web Bean injection into a servlet.  There are more areas in the JavaEE6 platform that can be used as Web Bean injection points - topics that will certainly be covered in future posts.  The sample for this blog can be found under the glassfish-samplesproject.  You can check out the code following these instructions.  Once the workspace is checked out, you can find this sample under glassfish-samples/ws/javaee6/webbeans/webbeans-servlet.  You can find documentation for the sample under glassfish-samples/ws/javaee6/webbeans/webbeans-servlet/docs. As with all the Web Beans samples now, you should run with GlassFish V3 - any build after September 2 2009.

Version 1.0.0.PREVIEW3 of Web Beans (the implementation for JSR 299 Contexts and Dependency Injection For Java EE) now uses the annotations fromJSR 330(Dependency Injection For Java) and it is available in GlassFish V3. 
In this entry, we'll look at a simple JSF 2 application that uses Web Beans and the JSR 330 annotations. There are other features available in this release of Web Beans which will be discussed in subsequent blog entries. This application is a simple "guess number" application which I'm sure we are probably all familiar with by now.  Let's start by taking a look at the application's UI markup.

Listing 1: User Interface Markup


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
  2. <html xmlns=""
  3.     xmlns:ui=""
  4.     xmlns:h=""
  5.     xmlns:f="">
  6.     <h:head>
  7.         <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  8.         <title>JSF 2.0 Web Beans Example</title>
  9.     </h:head>
  10.     <h:body>
  11.        <h:form id="NumberGuessMain">
  12.           <h:panelGrid styleClass="title-panel">
  13.              <h:outputText value="Guess Number" styleClass="title-panel-text"/>
  14.              <h:outputText value="Powered By JavaServer Faces 2.0 and Web Beans" styleClass="title-panel-subtext"/>
  15.           </h:panelGrid>
  16.           <div style="color: black; font-size: 24px;">
  17.              I'm thinking of a number between <span style="color: blue">#{game.smallest}</span> and <span style="color: blue">#{game.biggest}</span>. You have <span style="color: blue">#{game.remainingGuesses}</span> guesses.
  18.           </div>
  19.           <h:panelGrid border="1" columns="5" style="font-size: 18px;">
  20.              Number:
  21.              <h:inputText id="inputGuess" value="#{game.guess}" required="true" size="3" disabled="#{game.number eq game.guess}" validator="#{game.validateNumberRange}"/>
  22.              <h:commandButton id="GuessButton" value="Guess" action="#{game.check}" disabled="#{game.number eq game.guess}"/>
  23.              <h:commandButton id="RestartButton" value="Reset" action="#{game.reset}" immediate="true" />
  24.              <h:outputText id="Higher" value="Higher!" rendered="#{game.number gt game.guess and game.guess ne 0}"style="color: red"/>
  25.              <h:outputText id="Lower" value="Lower!" rendered="#{game.number lt game.guess and game.guess ne 0}"style="color: red"/>
  26.           </h:panelGrid>
  27.           <div style="color: red; font-size: 14px;">
  28.              <h:messages id="messages" globalOnly="false"/>
  29.           </div>
  30.           <h:outputStylesheet name="stylesheet.css" />
  31.        </h:form>
  32.     </h:body>
  33. </html>

Everything on this page is really just standard JSF 2.0 view markup.  I've emphasized  the  Expression Language  (EL) portions of the view, especially game because it refers to a contextual bean instance also known as a Web Bean.

  • Line 17: Binding to Web Bean properties
  • Line 21: Binding to Web Bean properties and validation method
  • Line 22, 23: Binding to Web Bean action method
  • Line 24, 25: Binding to Web Bean properties

As you can see, in JSF, binding to a Web Bean is no different than binding to a typical managed bean.

Supporting Classes And Annotations For The Applicaton

Let's take a look at some of the utility classes for the application, namely the classes that are used to generate a random number and some of the supporting annotations.

Listing 2: The "Random" Annotation

  1. package webbeansguess;
  3. import static java.lang.annotation.ElementType.FIELD;
  4. import static java.lang.annotation.ElementType.METHOD;
  5. import static java.lang.annotation.ElementType.PARAMETER;
  6. import static java.lang.annotation.ElementType.TYPE;
  7. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  8. import java.lang.annotation.Documented;
  9. import java.lang.annotation.Retention;
  10. import javax.inject.Qualifier;
  12. @Target( { TYPE, METHOD, PARAMETER, FIELD })
  13. @Retention(RUNTIME)
  14. @Documented
  15. @Qualifier
  16. public @interface Random {
  17. }

The JSR 330 @Qualifierannotation is used to make Random a binding type.   This will allow us to inject a random number into the application.

Listing 3: The "MaxNumber" Annotation

  1. package webbeansguess;
  3. import static java.lang.annotation.ElementType.FIELD;
  4. import static java.lang.annotation.ElementType.METHOD;
  5. import static java.lang.annotation.ElementType.PARAMETER;
  6. import static java.lang.annotation.ElementType.TYPE;
  7. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  8. import java.lang.annotation.Documented;
  9. import java.lang.annotation.Retention;
  10. import java.lang.annotation.Target;
  11. import javax.inject.Qualifier;
  13. @Target( { TYPE, METHOD, PARAMETER, FIELD })
  14. @Retention(RUNTIME)
  15. @Documented
  16. @Qualifier
  17. public @interface MaxNumber {
  18. }

Likewise, the @Qualifier annotation is used to makeMaxNumber a binding type that will allow us to inject the maximum number allowed (for a guess) in the application.

Listing 4: The "Generator" Class

  1. package webbeansguess;
  3. import;
  4. import javax.enterprise.context.ApplicationScoped;
  5. import javax.enterprise.inject.Produces;
  7. @ApplicationScoped
  8. public class Generator implements Serializable {
  9.     private static final long serialVersionUID = -7213673465118041882L;
  10.    private java.util.Random random = new java.util.Random( System.currentTimeMillis() );
  11.     private int maxNumber = 100;
  12.     java.util.Random getRandom() {
  13.         return random;
  14.     }
  15.     @Produces @Random int next() {
  16.         return getRandom().nextInt(maxNumber);
  17.     }
  18.     @Produces @MaxNumber int getMaxNumber() {
  19.         return maxNumber;
  20.     }
  21. }


  • Line 7: An instance of this class exists for the lifecycle of the application
  • Line 15: next() is a Web Beans producermethod.  It will get called by the Web Beans Manager to obtain an instance of the next random number.
  • Line 18: getMaxNumber() is also a Web Beansproducer method.  It will get called by the Web Beans Manager to obtain an instance ofmaxNumber - essentially returning the maximum number to "guess" in the application (in this case "100").

The Anatomy of a Simple Contextual Bean

Now that we have are utility classes and annotations in place, we can use them in our Web Bean.

Listing 5: The "Game" Contextual Bean

  1. package webbeansguess;
  3. import;
  4. import javax.annotation.PostConstruct;
  5. import javax.enterprise.context.SessionScoped;
  6. import javax.enterprise.inject.Instance;
  7. import javax.inject.Inject;
  8. import javax.inject.Named;
  9. import javax.faces.application.FacesMessage;
  10. import javax.faces.component.UIComponent;
  11. import javax.faces.component.UIInput;
  12. import javax.faces.context.FacesContext;
  14. @Named
  15. @SessionScoped
  16. public class Game implements Serializable {
  17.     private static final long serialVersionUID = 1L;
  19.     private int number;
  20.     private int guess;
  21.     private int smallest;
  23.     @MaxNumber @Inject
  24.     private int maxNumber;
  26.     private int biggest;
  27.     private int remainingGuesses;
  29.     @Random @Inject Instance<Integer> randomNumber;
  31.     public Game() {
  32.     }
  34.     public int getNumber() {
  35.          return number;
  36.     }
  38.     public int getGuess() {
  39.          return guess;
  40.     }
  42.     public void setGuess(int guess) {
  43.          this.guess = guess;
  44.     }
  46.     public int getSmallest() {
  47.          return smallest;
  48.     }
  50.     public int getBiggest() {
  51.         return biggest;
  52.     }
  54.     public int getRemainingGuesses() {
  55.         return remainingGuesses;
  56.     }
  58.     public String check() throws InterruptedException {
  59.         if (guess>number) {
  60.             biggest = guess - 1;
  61.         }
  62.         if (guess<number) {
  63.             smallest = guess + 1;
  64.        }
  65.        if (guess == number) {
  66.            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Correct!"));
  67.        }
  68.        remainingGuesses--;
  69.        return null;
  70.     }
  72.     @PostConstruct
  73.     public void reset() {
  74.         this.smallest = 0;
  75.         this.guess = 0;
  76.         this.remainingGuesses = 10;
  77.         this.biggest = maxNumber;
  78.         this.number = randomNumber.get();
  79.     }
  81.     public void validateNumberRange(FacesContext context,  UIComponent toValidate, Object value) {
  82.         if (remainingGuesses <= 0) {
  83.             FacesMessage message = new FacesMessage("No guesses left!");
  84.             context.addMessage(toValidate.getClientId(context), message);
  85.             ((UIInput)toValidate).setValid(false);
  86.             return;
  87.         }
  88.         int input = (Integer) value;
  89.         if (input < smallest || input > biggest) {
  90.             ((UIInput)toValidate).setValid(false);
  91.             FacesMessage message = new FacesMessage("Invalid guess");
  92.             context.addMessage(toValidate.getClientId(context), message);
  93.         }
  94.     }
  95. }

I've color coded the areas of interest in this class.  Theblue areas are JSR 299 (Web Beans) implementation details.  The red areas are JSR 330 (Dependency Injection For Java) areas.  The purple areas are the binding types.

  • Line 14: We are using the Namedannotation to associate a name with this bean.  Because there is no argument specified with the Named annotation, its name will be the name of the bean itself with the first letter lowercase (game).   This allows us to reference the bean by that name using the Expression Language in the view.
  • Line 15: We declare this bean as a session scoped bean, meaning it's lifecycle is the lifecycle of the session.
  • Line 23: The producer method in the Generator class (line 18) will service this injection point causing maxNumber to have a value of "100".
  • Line 29: The producer method in the Generator class (line 15) will service this injection point making a  randomNumber instance available for this Web Bean.
  • Line 72: We use a standard @PostConstruct annotation causing variable initialization (after this Web Bean is created).
  • Line 78: Our Web Bean has been created, so the randomNumber.get() call will cause theproducer method in theGenerator class (line 15) to get called.

Well, that's a quick overview of a simple JSF2 application that uses the Web Beans (JSR 299 implementation) and the Java Dependency Injection (JSR 330) annotations. You can find this version of Web Beans in any of the GlassFish V3 builds after September 2, 2009.

JSF Ajax frameworks have been around for some time. JSF is all about server side components that render their state as markup to the client. JSF has a well defined lifecycle that defines how component state is handled on the server and when component state is rendered to the client.  JSF Ajax frameworks can control which components are processed on the server (known as partial processing), and which components render themselves back to the client (known as partial rendering) by sending Ajax requests with special parameters. 

How ICEFaces Uses JSF 2.0  To Send Ajax Requests

The JSF 2.0 Ajax JavaScript API jsf.ajax.request can be used to trigger Ajax requests from an HTML event such as onclick.  This function can be called from within a JavaScript function too.  ICEFaces uses the jsf.ajax.requestfunction within their JavaScript library:

    submitEvent = function(event, element, form) {
        jsf.ajax.request(element, event, {execute: '@all', render: '@all'});

    submitForm = function(event, form) {
        jsf.ajax.request(form, event, {execute: '@all', render: '@all'});

ICEFaces uses submitEventand submitForm in theiriceSubmitPartial and iceSubmit functions respectively.  The iceSubmitPartial and iceSubmit functions are part of the ICEFaces Ajax Bridge that  communicate with the server.  ICEFaces is using the keyword @all for both execute and render which means that all components are processed on the server, and all components are targeted for rendering markup back to the client.  ICEFaces sends everything because on the server the framework determines the "dirty" regions in a view by comparing the current rendered view with the view that was rendered as a result of the Ajax request.

How ICEFaces Uses JSF 2.0 To Process Ajax Requests On The Server

JSF 2.0 provides extensibility points that allow JSF Ajax frameworks to perform customized partial processing and partial rendering on the server.  The JSF 2.0 API provides the javax.faces.context.PartialViewContext.processPartialmethod for this purpose.  This method performs partial processing and partial rendering on the components identified by the identifiers in the execute and render lists from the request.  ICEFaces extends javax.faces.context.PartialViewContextwith their DOMPartialViewContextimpementation:

import javax.faces.context.PartialViewContextWrapper;
public class DOMPartialViewContext extends PartialViewContextWrapper {
    public void processPartial(PhaseId phaseId)  {
        if (isRenderAll() && PhaseId.RENDER_RESPONSE) {
            // Perform DOM Diffing ..
            // Send updates as separate <update> elements using JSF 2.0 PartialResponseWriter
        } else {

If the current processing phase is the Render Response Phase, ICEFaces:
  • retrieves the current DOM (for the view before rendering)
  • generates the new DOM by rendering the new view (using a special DOMResponseWriter)
  • determines if there are differences between the DOMs
If there are differences, then the JSF 2.0 javax.faces.context.PartialResponseWriterimplementation is used to write <update> elements back to the client following the specification defined partial response format:

      <update id="user">
      <update id="password">

If there are no differences, then the JSF 2.0 javax.faces.context.PartialResponseWriterimplementation is used to write the single <update> element containing the entire view markup.


ICEFaces 2.0 is still under development, and it is one of the early component frameworks that follow the JSF 2.0 Ajax standard.  It uses the JSF 2.0 Ajax JavaScript API to initiate Ajax requests to the server.  It leverages the JSF 2.0 Ajax extensibility points on the server to process Ajax Requests and formulate the partial response to send back to the client.  This version of ICEFaces (2.0) currently uses the mojarra implementation of the JSF 2.0 specification.  There will surely be more component frameworks on board with JSF 2.0, which should go a long way towards component interoperability.


ICEFaces 2.0
JavaServer Faces 2.0 Specification
Project Mojarra

Andy Schwartz (Oracle Corp/JSF 2.0 EG member) and I will be speaking at Ajax World next week on JSF and Ajax Past, Present and Future

The session will explore the variety of JSF Ajax frameworks available today. Then you will get a preview of the Ajax work that is being standardized in the JSF 2.0 specification.

The JavaScript public API is the beginnings of the client side portion of the JavaServer Faces / Ajax standard. The JavaServer Faces 2.0 Expert Group includes members representing other JavaServer Faces / Ajax frameworks such as RichFaces, ADF Faces (Trinidad) and ICEfaces.

We're definitely exploring new territory here, as this is the first time that a public JavaScript API has been introduced with JavaServer Faces to the JCP. It may be the first time a public JavaScript API has been introduced to the JCP, period.

This demo uses the Dynamic Faces library (with JSF) to illustrate a stock lookup service. To simplify things for the demo, there are only three artifacts used in the demo: 
  1. One JSP page
  2. One small JavaScript file
  3. One Managed Bean
First, let's take a look at the UI:     

The UI is pretty basic. You enter one or more space delimited stock symbols in the "Symbols" text field and press the "Search" button. You can enter proxy information if you are behind a firewall. The most interesting feature of the demo is the "Streaming" option. If "Streaming" is set to "On", the client will poll the server, firing Ajax transactions every 10 seconds (or a specified time interval). The "Remote/Local" option allows you to switch the demo to use local data, if a network connection is not available. If the "Remote" option is used, the Yahoo Stock Quoting service is used to get the stock data. The table of stock data will dynamically change size depending on the number of symbols that are used in the query. Let's take a look at the artifacts used in this demo.


Here's a snippet of the JSP page for the demo, showing the relevant parts:

<script type="text/javascript">
  <h:form id="form" prependId="false">
    <h:panelGrid styleClass="title-panel">
        <h:outputText value="Stock Query" styleClass="title-panel-text"/>
        <h:outputText value="Powered By Dynamic Faces" styleClass="title-panel-subtext"/>
    <h:panelGrid border="1" columns="1" styleClass="panel-input-border">
        <h:panelGrid border="1" columns="7">
            <h:outputText value="Symbol:"/>
            <h:inputText id="symbol"/>
           <h:commandButton id="search" value="Search"
                onclick="DynaFaces.fireAjaxTransaction(this, {});return false;"
                actionListener="#{bean.getStockInfo}" />
            <h:outputText value="Proxy Host:"/>
            <h:inputText id="proxyHost"/>
            <h:outputText value="Proxy Port:"/>
            <h:inputText id="proxyPort"/>
            <h:outputText value="Streaming:"/>
           <h:selectOneMenu id="streaming" value="Off"
                <f:selectItem itemValue="Off" itemLabel="Off"/>
                <f:selectItem itemValue="On" itemLabel="On"/>
            <h:selectOneMenu id="connection" value="Local">
                <f:selectItem itemValue="Local" itemLabel="Local"/>
                <f:selectItem itemValue="Remote" itemLabel="Remote"/>
    <h:panelGrid id="stockdata" border="1" columns="8"
        styleClass="panel-data-border" rendered="false">
            <f:facet name="header">
                <h:outputText value="Symbol"/>
            <f:facet name="header">
                <h:outputText value="Name"/>
            <f:facet name="header">
                <h:outputText value="Open"/>
            <f:facet name="header">
                <h:outputText value="Last"/>
            <f:facet name="header">
                <h:outputText value=""/>
            <f:facet name="header">
                <h:outputText value="Change"/>
            <f:facet name="header">
                <h:outputText value="Change %"/>
            <f:facet name="header">
                <h:outputText value="Volume"/>

Here is an explanation of the "blue" sections in the code snippet: 
  1. <jsfExt:scripts/> is the standard tag to include for Dynamic Faces applications, and it includes the Dynamic Faces JavaScript library.
  2. The include_js('javascripts/stock-faces.js'); line is just a utility function that loads the application's JavaScript file stock-faces.js (which we will discuss next).
  3. The h:commandButton tag has an onclick JavaScript event handler attached to it -DynaFaces.fireAjaxTransaction, which will send an Ajax request to the server when the button is pressed. TheactionListener specified by #{bean.getStockInfo} will get executed on the server as usual. But the key is that any view or JSF component manipulation done on the server will happen over Ajax.
  4. The "streaming" option is just a h:selectOneMenucomponent that has an onchange JavaScript event handler.
  5. Next is the "placeholder" for our dynamic table of stock data. The attribute rendered is set to false, but this will be set to true from the application code when there is stock data to return.
Get the entire source of this file here.

Application JavaScript

var pollId;

/** Delay between requests to the server when polling. */
var pollDelay = 10000;

/** Start polling the server */
function start() {
    pollId = setInterval(poll, pollDelay);

/** Stop polling the server */
function stop() {

function poll() {
    DynaFaces.fireAjaxTransaction(null, {});

function queueEvent() {
    var actionEvent =
        new DynaFaces.ActionEvent("search",
    return false;

function toggleStreaming() {
    var menu = document.getElementById("streaming");
    var idx = menu.selectedIndex;
    var streaming = menu[idx].value;
    if (streaming == "Off") {
    } else if (streaming == "On") {

  1. The polling delay (or the time interval between calls to the server is 10 seconds.
  2. The start() function kicks off the server polling.
  3. The stop() function stops server polling.
  4. The poll() function does two things: 
    1. It queues up a server side JSF action event.
    2. Fires an Ajax request to the server using the Dynamic Faces library.
  5. The queueEvent() function queues up a server side <>JSF action event using the Dynamic Faces library. This action event will get processed during the standard JSF lifecycle processing as the Ajax request flows through.
  6. The toggleStreaming() function just toggles the value of the "streaming" menu control.
Get the entire source for this file here.

JSF Managed Bean (how original...)       
 * This bean has methods to retrieve stock information from
 * the Yahoo quote service.
public class Bean {

    private static final String SERVICE_URL =

     * Action method that is used to retrieve stock information.
     * This method uses two helper methods - one to get the
     * stock information, and the other to dynamically build
     * the "data" components for the UI.
    public void getStockInfo(ActionEvent ae) {
                       stockData = getStockData(symbols);

     * Helper method to get the stock data (remotely).
    private String[] getStockData(String[] symbols)
        throws IOException, MalformedURLException {
        String[] data = new String[symbols.length];
        for (int i=0; i<symbols.length; i++) {
            StringBuffer sb = new StringBuffer(SERVICE_URL);
            String url = sb.toString();
            URLConnection urlConn = null;
            InputStreamReader inputReader = null;
            BufferedReader buff = null;
            try {
                urlConn = new URL(url).openConnection();
                inputReader = new InputStreamReader(
                buff = new BufferedReader(inputReader);
                data[i] = buff.readLine();
                data[i] = data[i].replace( "\"", "" );
        return data;

     * Helper method to dynamically add JSF components to display
     * the data.
    private void buildUI(String[] stockData){
        FacesContext context = FacesContext.getCurrentInstance();
        UIForm form = (UIForm)context.getViewRoot().findComponent("form");
        UIPanel dataPanel = (UIPanel)form.findComponent("stockdata");
        String buffer = null;
        for (int i=0; i<stockData.length; i++) {
            String[] data = stockData[i].split("\\,");
            UIOutput outputComponent = null;
            UIGraphic imageComponent = null;
            // Create and add components wth data values

            // Symbol

            outputComponent = new UIOutput();

            // Name

            outputComponent = new UIOutput();

            // Open Price (if any)

            outputComponent = new UIOutput();
            try {
                openPrice = new Double(data[2]).doubleValue();
            } catch (NumberFormatException nfe) {
                openPriceAvailable = false;

This JSF Managed Bean has an action method getStockInfo that does two things: 
  1. It uses a helper method getStockData to contact the Yahoo Stock Quote service (as defined by SERVICE_URL) to retrieve stock data for all the symbols.
  2. It uses a helper method buildUI to build JSF components (from the stock data) and it adds the JSF components to the JSF component view. After all components have been created and added, then it sets the rendered attribute to true on the "stockdata" JSF component.
The action method, getStockInfo is called on two seperate occasions: 
  1. It is called when the "Search" button is pressed.
  2. It is also called as the result of an Ajax "poll" request. This is because each client poll queues an action event tied to this event handler. Refer to the queueEvent method in thestock-faces.js JavaScript file.
Get the entire source of this file here.


We've seen how we can combine the power of JSF component building with Ajax to produce dynamic applications. This application illustrated the use of two features from Dynamic Faces: 
  1. fireAjaxTransaction
  2. Remote JSF event queueing from JavaScript
This application is included as one of the samples applications in the jsf-extensions project. Please refer to the jsf-extensions FAQ for getting and building the source code.


The core MobileFaces library is currently based on the JSF 1.1 specification. The library not only makes it easier to develop mobile web applications, but it also utilizes a key extensible piece of the JSF architecture - RenderKits andRenderers. This allows the same underlying component model to render not only in HTML, but markup that is suitable for mobile devices (such as WML). Here, we'll take a look at how we can get one of the sample Mobile JSF Kit applications up and running on the GlassFish application server.

  1. A working build environment with ant, at least JDK 5, and GlassFish. I've recently run MobileFaces and the Mobile JSF Kit on the GlassFish v2 B52 Promoted Build.
  1. Download and unpack the Mobile Faces Source to some directory, sayMobileFaces.
  2. Go to the MobileFaces directory. Get the build.xml script and the associated file for GlassFish from here and unpack it in the MobileFaces directory. Edit theglassfish.home property in file to refer to your GlassFish top level directory.
  3. Build MobileFaces from source: ant -f build.xml.glassfish build
  4. Download and unpack the Mobile JSF Kit. After you unpack it you will see asamples directory.
  5. Go to the HelloMobile directory under thesamples directry - this will be the sample application we'll be running. Currently, the build scripts are set up to work with Tomcat. Get the build.xml script and the associated file for GlassFish from here and unpack it in the HelloMobile directory. Edit theglassfish.home property in file to refer to your GlassFish top level directory. Edit the mobilfaces.home property in the file to refer to your MobileFaces directory.
  6. Build the HelloMobile application: ant -f build.xml.glassfish build
  7. Start the GlassFish application server (if it's not already started) and deploy the application to the GlassFish application server. The helloMobile_R1A.war file will be under theHelloMobile/dist directory. The application will be deployed as: helloMobile_R1A
Running the Application:

To test your mobile web application you can use a phone simulator with a mobile browser. Here, we will use the Openwave Phone Simulator with the Openwave Mobile Browser. The simulator uses the same browser that is embedded in real mobile phones. I believe this simulator only works on Windows - but they may have a Linux version available as well. 
  1. Download and install the Openwave Phone Simulator from here.
  2. Start up the phone simulator. In addition to the phone simulator you will see a console window for the simulator.
    phone-simulator.GIF simulator-console.GIF
  4. Configure the phone simulator to your environment. UnderSettings select Server Profiles. There you can set your network settings. I used http-direct with no proxy.
  5. Configure the phone simulator with the appropriateUser-Agent. To test the WML rendering capabilities of MobileFaces, go to Settings, then Device Settings, and change the User Agent field to:OPWV-SDK-WML.
  6. Enter the URL http://localhost:8080/helloMobile_R1A in the phone simulator URL field and press "enter".
Now you should see the application loaded into the simulator. You can also see the page content sent in the response in the simulator console window:      
phone-simulator-1.GIF simulator-console-1.GIF

Under The Hood:

The MobileFaces architecture includes a servlet filter that examines the user-agent information on the incoming request. The architecture also extends the JSFRenderKitFactory to load up RenderKits for xhtmL-MP and WML in addition to the Standard HTML RenderKit. The extensibility of the JSF architecture allows you to create additional RenderKits. Based on the user-agent it will create the appropriate RenderKit that will render the markup in the JSF Render Response Phase. MobileFaces also includes a small library of custom tags to use in your pages and these can be used along with the Standard HTML JSF tags.


GlassFish Application Server
Mobile JSF Kit
JavaServer Faces

It's also worth noting that there is a Mobile JSF Kit Netbeans plugin available for download at the Mobile JSF site. But that's a topic for discussion on another day..  
To get prior releases of Seam running on GlassFish, you had to patch some Seam application modules. With this release, there is no patchwork necessary - the folks at JBoss (RedHat) have done a great job of streamlining the process. In fact, after you download and unpack the Seam 1.1.0.GA release from here, you will see a GlassFish sample application (which is essentially the booking application) under the "jboss-seam-1.1.0.GA\examples\glassfish" directory. In this entry, we will outline the steps to get this release of Seam running on GlassFish with Java Persistence.

  1. A working build environment with ant, at least JDK 5, and GlassFish. I've run this version of Seam successfully on the GlassFish v1 FCS (v1_ur1-p01-b02) and GlassFish v2 (Build 30) builds.
Seam Setup:
  1. Download and install the Seam 1.1.0GA release from here.  You should see a jboss-seam-1.1.0.GA directory.
  2. Go to the jboss-seam-1.1.0.GA/examples/glassfish directory.
  3. Build the sample application using the "toplink" build target: 
    • ant clean; ant toplink
    The "toplink" target builds the EAR file using toplink as the JPA provider.
Deploy the application:
  1. Start up GlassFish:   <glassfish install dir>/bin/asadmin start-domain domain1
  2. Start the database:  <glassfish install dir>/bin/asadmin start-database
  3. Deploy jboss-seam-1.1.0.GA/examples/glassfish/build/jboss-seam-glassfish.ear
Load the database:
  1. Get the sql script that will be used to load the database fromhereand unpack it to some directory. You should see the script: import.sql
  2. Go to the directory that contains the import.sqlscript.
  3. Set your CLASSPATH to include: 
    • <glassfish install dir>/javadb/lib/derbyclient.jar
    • <glassfish install dir>/javadb/lib/derbytools.jar
    • <glassfish install dir>/javadb/lib/derby.jar
  4. Get into the "ij" utility: java
  5. At the "ij>" prompt: 
    • ij> DRIVER 'org.apache.derby.jdbc.ClientDriver';
    • ij> CONNECT 'jdbc:derby://localhost:1527/sun-appserv-samples';
    • ij> run 'import.sql';
  • Now the Seam application tables should be loaded.
Run the application:
  • visit localhost:8080/jboss-seam-glassfish
So far we've seen how we can get Seam running on GlassFish with Hibernate Persistence and Java Persistence. Modifications were needed to the Seam core classes as well as the application classes. Fortunately, JBoss has made the modifications to their core classes in time for their Seam FCS release. In this entry we'll outline the steps to get the Seam FCS release up and running on GlassFish with Java Persistence.

  1. A working build environment with ant, at least JDK 5, and GlassFish (build 43 or later).
  2. You'll need to use some of the Hibernate libraries that the Seam framework depends on:
Seam Setup:
  1. Download and install the Seam 1.0.1.GA release from here.  You should see a jboss-seam-1.0.1.GA directory.
  2. Get the zip file:
  3. Go to the jboss-seam-1.0.1.GA directory and unzip
Compilation Procedure:
  1. Copy jboss-seam-1.0.1.GA/lib/thirdparty-all.jar to <glassfish install dir>/lib 
  2. Compile Seam core classes - this will compile the HtmlLink class in the ui package.
  3. Compile Seam Booking Application:
Deploy the application:
  1. Start up Glassfish.
  2. Start the database:  <glassfish install dir>/bin/asadmin start-database
  3. Deploy jboss-seam-1.0.1.GA/examples/booking/build/jboss-seam-booking.ear
Load the database:
  1. Go to jboss-seam-1.0.1.GA/examples/booking/resources
  2. set your CLASSPATH so that it is:
  3. java -Dij.driver='org.apache.derby.jdbc.ClientDriver'
  4. At the Derby ij prompt connect to the default database:
  • Now the Seam application tables should be loaded.
Run the application:
  • visit localhost:8080/seam-booking

Code Change Summary

The following changes apply to the Seam Booking application:

----> Added trailing semicolons to each sql statement
----> Updated for application with GlassFish and Java Persistence
----> Updated per EJB 3 schema: added schema namespace and <interceptors> element
----> Added schema namespace
---->Updated JNDI lookup pattern
---->Disabled MyFaces StartupServletContextListener - we're using JSF 1.2
---->Added <ejb-local-ref> elements for EJB applicaton actions
----> Updated sql statements passed to EntityManager.createQuery
---->Refer to table name 'Users'
---->Added <ui:composition> element

The following change is to a Seam (JSF) custom component:

---->Added encodeEnd method to properly end either an HTML input element or an HTML hyperlink element

All of these entries are in the file and can be reviewed.  
Often when you are "heads down" developing a technology, you forget about who might be using that technology. And in the course of giving a presentation about the technology, you may hear a question or two like "yeah... great.... but who is using this out there in the real world?".. Well.. we've compiled an initial list of companies/sites out there that use JSF.... That list can be foundhere. Enjoy!