Wednesday January 24, 2007
Dynamic Faces, Part 1: Using fireAjaxTransaction to Ajaxify a JavaServer Faces component
This blog is the first in a series on how to use the basic features of Dynamic Faces to add Ajax capabilities
to JavaServer Faces components that you already know and love. The topic of this first blog is how to use
the fireAjaxTransaction function provided by Dynamic Faces to perform Ajax updates at the component level.
This series assumes you know the basics of JavaServer Faces Technology.
Before going on, you might want to skim through this article to get an overview of what Dynamic Faces is all about: New Technologies for Ajax and Web Application Development: Project Dynamic Faces.
Throughout this blog series, I'll use a simple example that uses standard JavaServer Faces components along with Dynamic Faces to allow users to do the following:
If you were using plain JavaServer Faces technology without Dynamic Faces, you would need to add a button to update the varieties menu and the variety description, and you would have to go through a full-page refresh to do the update.
With Dynamic Faces, you can get rid of the button and rely on Dynamic Faces to do the work of updating these components using Ajax.
To see this example in action, download simpleDynamicFaces.war from the samples folder of the
download page for the JSF Extensions project and deploy the WAR file.
To create an example like this one, the first thing to do is to download the JSF Extensions project, which includes Dynamic Faces, and perform the simple set-up steps described in Setting up an Application to Use Dynamic Faces in the article mentioned previously. After that, you're ready to start coding.
Behind the scenes, Dynamic Faces performs all the Ajax functionality through the use of a set of JavaScript libraries. One of the JavaScript functions that Dynamic Faces provides is the fireAjaxTransaction function. As its name suggests,
it fires an Ajax request in response to a particular event, such as clicking on a component. As such, this function gives you component-level
control over what is updated in your page. To use the fireAjaxTransaction function, you do the following:
DynaFaces.fireAjaxTransaction function.fireAjaxTransaction to update components
via Ajax, as shown on lines 10 and 16. Notice on lines 11 and 17 that I have used the standard valueChangeListener tag attributes to register value-change events on the fruit
and variety components. I'll get to the importance of this later on.
<f:view> ... <h:form prependId="false" id="form"> <h:panelGrid columns="2" cellpadding="4"> <h:outputText value="Select a fruit:"/> <h:outputText value="Select a variety:"/> <h:selectOneRadio id="fruit" value="#{fruitInfoBean.fruit}" onclick="DynaFaces.fireAjaxTransaction(this, { execute: 'fruit'});" valueChangeListener="#{fruitInfoBean.changeFruit}"> <f:selectItems value="#{fruitInfoBean.fruits}"/> </h:selectOneRadio> <h:selectOneMenu id="variety" value="#{fruitInfoBean.variety}" onchange="DynaFaces.fireAjaxTransaction(this, { execute: 'variety' });" valueChangeListener="#{fruitInfoBean.updateVariety}"> <f:selectItems value="#{fruitInfoBean.varieties}"/> </h:selectOneMenu> </h:panelGrid> <h:outputText id="varietyInfo" value="#{fruitInfoBean.varietyInfo}" /> </h:form> </f:view>
The first thing I did in the page is I set the form tag's prependId attribute to false so that I can refer to component
IDs without prepending the form's ID. This attribute
was added in JavaServer Faces technology 1.2. In Ajax applications, you often have to refer to client IDs. Without the prependId attribute, you'd have to add the form ID to every client ID reference, which adds extra bytes to network transactions and is a pain to type. Remember, with Ajax, you are doing more transactions, so you want each one to be as small as possible.
After setting the prependId attribute, I added an onclick attribute to the fruit selectOneRadio tag and set it to the following call to fireAjaxTransaction:
"DynaFaces.fireAjaxTransaction(this, { execute: 'fruit'});"
The this parameter is a JavaScript reference that is the DOM element for the markup generated by the fruit selectOneRadio tag.
The other parameter is a kind of JavaScript Object known as an associative array, in which the keys are strings and the values are whatever you want them to be. Each key/value pair represents an option that you pass to the fireAjaxTransaction function.
These options tell Dynamic Faces which parts of the component tree it needs to process and re-render using Ajax. The Dynamic Faces JavaScript Library Reference includes the complete list of acceptable options.
In this case I have only one option, execute: 'fruit', which says that the
fruit component (and its children, if it has any) must go through the execute portion of the
JavaServer Faces life cycle. This part of the life cycle includes the phases
responsible for converting and validating data, updating model values, and handling action events.
I did not include the render option because I want all components to be re-rendered as a result of this action, which is the default behavior.
As shown on line 10 of the preceding JSP page, the fireAjaxTransaction function is called when the user clicks on a radio button. When this happens, the fruit component goes through the execute phase of the life cycle, and the value-change event that is registered on it is fired.
The
valueChangeListener attribute of the fruit component tag references the changeFruit method, which handles the value-change event (see FruitInfoBean.java). The changeFruit
method performs some model updates when the fruit component is activated.
Therefore, the fruit component must go through the execute phase of the life cycle so that these model updates will occur.
The changeFruit method updates the model value of the variety menu component with the list of varieties corresponding to the fruit
the user chose from the fruit component.
For example, if the user selects Pear from the fruit component, the variety component will display the values Aurora, Bartlet, Bosc, Comice, and Delicious.
The changeFruit method also sets the currently
selected fruit value to the first variety in the list. Finally, it updates the varietyInfo output component so that
the description of a variety corresponds to the currently selected fruit variety. For example, if the user chooses Pear, Aurora is the selected value of the variety component, and the varietyInfo component displays this message:
Aurora: Sweet, juicy, and aromatic. Quality dessert pear ...
When Dynamic Faces re-renders these components using Ajax, the components will display with the new values.
I also used the fireAjaxTransaction function with the variety component:
"DynaFaces.fireAjaxTransaction(this, { execute: 'variety'});"
This function call works the same way as it does for the fruit component: It causes the variety component to go through the execute phases of the life cycle and re-renders all components via Ajax.
As with the fruit component, the variety component has a value-change event registered on it. Like the changeFruit method, the updateVarety method, which handles this event also updates model values. The updateVariety method updates the varietyInfo
component's model value so that the displayed description of a fruit variety corresponds to the variety the
user selected from the variety component menu.
That's all there is to it. For this example, you do not need to write any JavaScript code to use Ajax, nor do you need to do anything special in your Java code. And the best part is that you can use the JavaServer Faces components you already know and use without modifying them.
Posted at 12:46AM Jan 24, 2007 by jenniferb in Sun | Comments[7]
Friday January 19, 2007
Still More Fun with jMaki: Loading data into a Dojo table using JSON APIs
OK, I think I've exhausted the "More Fun with jMaki" moniker. But that doesn't mean I won't write more about jMaki. Upcoming blogs include how to wrap a Dojo widget into a jMaki widget. This time, I'll show how to load your own data into a Dojo table. This blog focusses only on how to convert Java object data into JSON format. It doesn't detail getting the data from a database.
The first thing to determine is what format the data for the Dojo table needs to be. To do this, you look at the widget.json file for the table widget. This file is located in the resources/dojo/table directory of the jMaki samples download. As the default value, it shows the following:
"defaultValue":{
"columns": { "title" : "Title",
"author":"Author",
"isbn": "ISBN #",
"description":"Description"},
"rows":[
['JavaScript 101', 'Lu Sckrepter','4412', 'Some long description'],
['Ajax with Java', 'Jean Bean','4413', 'Some long description']
]
}
In JSON-speak, this means that you have a JSON object (denoted by the outer curly braces) that contains another JSON object representing the columns of the table (denoted by the inner set of curly braces) and an array representing the rows of data (denoted by the square brackets). Inside the rows array is a set of other arrays. Each one of those arrays represents a single row of data.
What you need to do is use the JSON APIs to convert Java object data into this JSON format.
First, I created a Book bean to represent a book. If you are using the Java Persistence API, you could make this an entity class. Here is part of the Book class:
public class Book {
private int bookId;
private String title;
private String firstName;
private String surname;
/** Creates a new instance of Book */
public Book(int bookId,
String title,
String firstName,
String surname) {
this.bookId = bookId;
this.title = title;
this.firstName = firstName;
this.surname = surname;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
... // other getter and setter methods for the other properties.
Next, I created a class to convert the data to JSON. In this class, I added a method to create some rows of data. This is where you'd normally do your database access:
public List createBooks() throws Exception {
ArrayList books = new ArrayList();
Book book =
new Book(201,
"My Early Years: Growing up on *7",
"Duke", "");
books.add(book);
book =
new Book(202,
"Web Servers for Fun and Proft",
"Jeeves", "");
books.add(book);
book =
new Book(203,
"Web Components for Web Developers",
"Webster", "Masterson");
books.add(book);
return books;
}
Now comes the method that converts this data into JSON format using the JSON APIs:
public JSONArray getBookData() throws Exception {
JSONArray books = new JSONArray();
JSONArray book = new JSONArray();
ArrayList bookList =
(ArrayList)createBooks();
Iterator i = bookList.iterator();
while(i.hasNext()){
Book bookData = (Book)i.next();
book.put(bookData.getBookId());
book.put(bookData.getTitle());
book.put(bookData.getFirstName());
book.put(bookData.getSurname());
books.put(book);
book = new JSONArray();
}
return books;
}
This method uses the JSONArray API to create the rows array that contains an array representing each row of data. I'll explain in a minute why I'm not creating the column data here.
Finally, you refer to the getBookData method from the page using an EL expression:
<jsp:useBean id="appBean"
class="overviewApp.ApplicationBean"
scope="session"/>
<a:ajax name="dojo.table"
value="{columns: {'isbn':'ISBN #',
'title':'Title',
'firstName':'First Name',
'surname':'Last Name'},
rows:${appBean.bookData}}"/
>
Notice that I had to manually enter the columns data, but I can reference the rows data in the bean. This is because the JSONObject API uses HashMap under the covers. As you might know, HashMap does not ensure insertion order. Our use case requires it so that the column headings match up with the row data in each column. Therefore, I manually entered the column data into the page. If it were not for this issue, we could create the table as a JSON object in the bean so that the page author could reference the entire table with one EL expression.
Posted at 11:21AM Jan 19, 2007 by jenniferb in Sun | Comments[25]
Monday January 08, 2007
More Fun with jMaki: Getting Data From a Bean
My last blog featured a combobox widget that includes a list of European cities. The service attribute of the ajax tag representing the widget in the page points directly to a JavaScript file that includes the data in a format that JavaScript can evaluate:
[ ["Berlin","Berlin"], ["Helsinki","Helsinki"], ["London","London"], ["Madrid","Madrid"], ["Paris","Paris"], ["Rome","Rome"] ]It is a JavaScript array representing the set of values in the combobox. This array consists of a set of other JavaScript arrays. Each of those JavaScript arrays includes the displayed label and the actual value of an item in the combobox.
OK, but what if you want to get the data from a bean using an EL expression, as you can with most other JSP tags? You can, but you need to add a little bit of code that will convert the object representation of your data into the representation shown above so that JavaScript can evaluate it.
This sounds like a lot of work, but it's really not bad. What I did is I created a bean, added the property to set the city name, and added a small method to build the JavaScript array of the data using JSON, which is a library that converts objects into String representations that JavaScript can evaluate. The JSON APIs are included in jMaki. Let's see how we can use JSON with our example.
Instead of using cities, lets use a set of countries and their country codes as our data instead:
[
["Japan","JP"],
["Thailand","TH"],
["Uganda", "UG"],
["Ukraine","UK"],
["United States of America","USA"]
]
In your bean, you need to import the jMaki libraries and the JSON libraries included in jMaki:
import com.sun.jmaki.*; import org.json.*;Then you create your properties to get and set the data:
public String getCountry () {
return country;
}
public void setCountry(String country) {
this.country = country;
}
private String[] countries =
new String[] {
"Japan", "Thailand", "Uganda", "Ukraine",
"United States of America"
};
private String[] countryCodes =
new String[] {
"JP", "TH", "UG", "UR", "USA"
};
Now, you need to use JSON to convert that data to a form JavaScript can evaluate:
public JSONArray getCountryService() {
JSONArray countriesData = new JSONArray();
JSONArray countryData = new JSONArray();
for (int loop=0; loop < countries.length; loop++){
countryData.put(countries[loop]);
countryData.put(countryCodes[loop]);
countriesData.put(countryData);
countryData = new JSONArray();
}
return countriesData;
}
In getCountryService, we're looping through the list of countries and country codes and loading each country and its corresponding country code into a separate array. Then we're adding each array to the countriesData array. What this method returns is the array containing the set of arrays of country data that the combobox widget expects.
The last thing to do is to reference the bean from the ajax tag representing the combobox widget:
<jsp:useBean id="appBean" class="combobox.ApplicationBean" scope="session"/>
<a:ajax id="cb1" name="dojo.combobox" selected="${appBean.country}"
value="${appBean.countryService}" />
To use the bean that you created in your page, you need to add the jsp:useBean tag, as shown in the preceding code. Then, you can use EL expressions to access the data from the bean. You can access the selected value of the combobox by referencing the country property from the selected attribute. And, you can get the set of data for the combobox by referencing the getCountryService method.
That's all there is to it. Next time, I'll show how to use JSON to load data from a bean into a dojo etable.
Posted at 08:20AM Jan 08, 2007 by jenniferb in Sun | Comments[1]
Thursday January 04, 2007
Fun with jMaki: Using the Yahoo Geocoder service with the Dojo Combobox
Those of you who've looked at jMaki have probably seen the document on how to use the XMLHttpProxy to access services from widgets (See https://ajax.dev.java.net/xmlhttpproxy.html). In the document, Greg talks about the Yahoo Geocoder service. He also created a demo that uses the service with a Yahoo map widget.
I wanted to see how easy it would be to use the Geocoder service with the Dojo combobox widget included with jMaki. It turns out that there wasn't much to it.
My example allows a user to select a city from the combobox to see it plotted on the map, as shown in this figure:
To build this application, I first created my data file, europeCities.js, which contains a list of European cities in a JavaScript file:
[ ["Berlin","Berlin"], ["Helsinki","Helsinki"], ["London","London"], ["Madrid","Madrid"], ["Paris","Paris"], ["Rome","Rome"] ]
Next, I created the JSP page that includes the ajax tags that represent the combobox and the map:
<a:ajax id="cb1" name="dojo.combobox" service="europeCities.js" />
<p>
<a:ajax id="map001"
name="yahoo.map"
args="{zoom:10,
centerLat:37.39316,
centerLon:-121.947333700,
width:350}" />
The cb1 ajax tag represents the combobox. It gets its data from the europeCities.js file. The map001 ajax tag represents the yahoo map and is set to a default set of coordinates.
To get the city that the user selects to be plotted on the map, I first needed a topic listener that takes the value of that city and uses dojo.io.bind to do the following:
jmaki.addGlueListener({
topic: "/dojo/combobox/updateMap",
action: "call",
target: {object:"jmaki.listeners.ComboboxGeocoder",
functionName:"updateMapHandler"}});
jmaki.listeners.ComboboxGeocoder = {
updateMapHandler : function(args) {
var location = encodeURIComponent("location="+ args.value);
dojo.io.bind({
url: "xhp?key=yahoogeocoder&urlparams=" + location,
method: "get",
mimetype: "text/json",
load : function(type, data) {
jmaki.publish("/yahoo/geocoder", data.coordinates);
}
});
}
}
The /yahoo/geocoder topic listener is already included with the jMaki distribution. This listener function plots the coordinates on the map.
To get my new listener to be called when a new value is selected, I needed to add code to dojo combobox widget's component.js file that publishes the selected value and other arguments on the widget tag to the updateMap topic when the combobox experiences a value change:
this.onChange = function(value){
if (value == '') return;
jmaki.publish("/dojo/combobox/updateMap", {wargs: wargs, value: value});
}
That's all there is to it.
You can download this application from the jMaki file download page by selecting comboboxGeocoder.war from the list of files.
If you are using a proxy server to server your web requests, you need to specify the proxyHost and proxyPort context parameters in the web.xml file:
<context-param> <param-name>proxyHost</param-name> <param-value>myProxy.com</param-value> </context-param> <context-param> <param-name>proxyPort</param-name> <param-value>8080</param-value> </context-param>
To edit the web.xml file, unpack the WAR file and then re-package it with the jar command after editing the file.
Thanks to Greg Murray for helping me debug the listener code.
Posted at 12:48AM Jan 04, 2007 by jenniferb in Sun | Comments[31]