Miles to go …

September 17, 2008

TOTD #45: Ajaxifying Java Server Faces using JSF Extensions

Filed under: javaserverfaces, netbeans, totd — arungupta @ 5:00 am

TOTD #42 explained how to create a simple Java Server Faces application using NetBeans 6.1 and deploy on GlassFish. In the process it explained some basic JSF concepts as well. If you remember, it built an application that allows you to create a database of cities/country of your choice. In that application, any city/country combination can be entered twice and no errors are reported.

This blog entry extends TOTD #42 and show the list of cities, that have already been entered, starting with the letters entered in the text box. And instead of refreshing the entire page, it uses JSF Extensions to make an Ajax call to the endpoint and show the list of cities based upon the text entered. This behavior is similar to Autocomplete and shows the suggestions in a separate text box.

Let’s get started!

  1. Download latest JSF-Extensions release.
  2. Unzip the bundle as:
    ~/tools >gunzip -c ~/Downloads/jsf-extensions-0.1.tar.gz | tar xvf -
  3. In NetBeans IDE, add the following jars to Project/Libraries

  4. Edit “welcomeJSF.jsp”
    1. Add the following to the required tag libraries

      <%@taglib prefix=”jsfExt” uri=”http://java.sun.com/jsf/extensions/dynafaces” %>

      The updated page looks like:

    2. Add the following tag as the first tag inside <f:view>
      <jsfExt:scripts />

      The updated page looks like:

    3. Add prependId=”false” to “<h:form>” tag. The updated tag looks like:

    4. Add the following fragment as an attribute to <h:inputText> tag with “cityName” id:
      onkeyup=”DynaFaces.fireAjaxTransaction(this, { execute: ‘cityName’, render: ‘city_choices’, immediate: true});”

      This is the magic fragment that issues an Ajax call to the endpoint. It ensures execute portion of the request lifecycle is executed for “cityName” and “city_choices” (defined later) is rendered.

      The updated page looks like:

    5. Add a new <h:outputText> tag after <h:commandButton> tag (to hold the suggestions output):
      <h:outputText id=”city_choices” value=”#{dbUtil.cityChoices}”></h:outputText>

      The updated page looks like:

  5. Add the following fragment to web.xml
           <init-param>
              <param-name>javax.faces.LIFECYCLE_ID</param-name>
              <param-value>com.sun.faces.lifecycle.PARTIAL</param-value>
            </init-param>

    The updated file looks like:

  6. Edit “server.Cities” class
    1. Add a new NamedQuery in Cities class (at the mark after yellow-highlighted parentheses):

      The query is:

      @NamedQuery(name = “Cities.findSimilarName”, query = “SELECT c FROM Cities c WHERE LOWER(c.cityName) LIKE :searchString”),

      This NamedQuery queries the database and return a list of city names that matches the pattern specified in “searchString” parameter.

    2. Change the toString() method implementation to return “cityName”. The updated method looks like:

      This allows the city name to be printed clearly.

  7. Add a new method in “server.DatabaseUtil” as:
        public Collection<Cities> getCityChoices() {
            Collection<Cities> allCities = new ArrayList<Cities>();

            if (cities.getCityName() != null && !cities.getCityName().equals(“”)) {
                List list = entityManager.createNamedQuery(“Cities.findSimilarName”).
                        setParameter(“searchString”, cities.getCityName().toLowerCase() + “%”).
                  
          getResultList();
                for (int i = 0; i < list.size(); i++) {
                    allCities.add((Cities) list.get(i));
                }
               
            }
            return allCities;
        }

    This method uses previously defined NamedQuery and adds a parameter for pattern matching.

Now, play time!

The list of created cities is:

If “S” is entered in the text box (http://localhost:8080/Cities/), then the following output is shown:

Entering “San”, shows:

Entering “Sant” shows:

Entering “De” updates the page as:

And finally entering “Ber” shows the output as:

So you built a simple Ajaxified Java Server Faces application using JSF Extensions.

Here are some more references to look at:

  1. JSF Extensions Getting Started Guide
  2. Tech Tip: Adding Ajax to Java Server Faces Technology with Dynamic Faces
  3. JSF Extensions Ajax Reference

Java Server Faces 2.0 has Ajax functionality integrated into the spec and this should be more seamless. I’ll try that next!

Please leave suggestions on other TOTD (Tip Of The Day) that you’d like to see. A complete archive of all tips is available here.

Technorati: totd mysql javaserverfaces netbeans glassfish ajax

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot
Related posts:
  1. TOTD #46: Facelets with Java Server Faces 1.2
  2. TOTD #51: Embedding Google Maps in Java Server Faces using GMaps4JSF
  3. TOTD #94: A simple Java Server Faces 2.0 + JPA 2.0 application – Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3
  4. TOTD #95: EJB 3.1 + Java Server Faces 2.0 + JPA 2.0 web application – Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3
  5. TOTD #42: Hello JavaServer Faces World with NetBeans and GlassFish

3 Comments »

  1. Here are some other useful resources you should refer people to:

    Old, but good overview article:
    http://java.sun.com/developer/technicalArticles/J2EE/webapp_3/

    Great tutorial that actually explains how DF works and comes with a downloadable code example:
    https://jsf-extensions.dev.java.net/mvn/tutorial.html

    Comment by Jennifer — September 17, 2008 @ 8:51 am

  2. [Trackback] This blog updates TOTD #45 to use Facelets as view technology. Powerful templating system, re-use and ease-of-development, designer-friendly are the key benefits of Facelets. Facelets are already an integral part of Java Server Faces 2.0. But this blo…

    Comment by Arun Gupta's Blog — September 22, 2008 @ 6:05 am

  3. [Trackback] Java Server Faces 2.0 specification (JSR 314, EDR2) and implementation (soon to be EDR2) are brewing. This blog shows how to get started with Mojarra – Sun’s implementation of JSF. GlassFish v2 comes bundled with Mojarra 1.2_04 which allows…

    Comment by Arun Gupta's Blog — October 14, 2008 @ 5:55 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.
Powered by WordPress