JSON Interactions Between Server-Side Java and Client-Side YUI

ecause it facilitates communication via an interoperable format, JavaScript Object Notation (JSON), the Yahoo! User Interface library (YUI) allows you to implement the server side in any technology. The server will render JSON text for a given request, and YUI parses the JSON response to create JavaScript variables for use in UI widgets.

Using a Java server-side implementation, this article demonstrates the server-side interaction for fetching and persisting data with the YUI library DataTable widget. A number of Java frameworks are available for bridging the Java server-side layer and JavaScript UIs developed with YUI. JAbsorb, an AJAX framework that renders JSON response text to the client, is the framework used in this article.

JSON Breakdown

JSON is a lightweight format for serializing object attributes to be able to transmit from the server to the client or vice versa. Here is a sample:

{"checking":  {"balance":879.780029296875,   "openedOn":"Sun Jul 19 20:33:30 PDT 2009",   "number":123456   }}

This is the JSON representation of the Java class BankAccount:

class BankAccount {   public static final int CHECKING = 0;   public static final int SAVINGS = 1;      private int type;   private int number;   private float balance;   private Date openedOn;      }

The server renders this response for a request like this:

http://localhost:8080/pwds/GetBankDetails?id=1

JSON-RPC

JAbsorb is a lightweight AJAX framework for exposing Java objects on the server to JavaScript client programs. It tunnels every method call to the JavaScript proxy object, passes it to the server-side instance, and passes the response back to the JavaScript program.

The demonstration in this article implements a servlet to parse requests from the client program and delegate them to their corresponding server-side functions. Keep in mind that this approach runs the risk of making fine-grained requests to the server and thereby degrading performance.

The servlet JSONServlet is an abstract base class that parses the request, delegates to an AJAX function class, and renders the response returned by the function. The implementation looks like Listing 1.

A typical AJAX function class that uses the JSONServlet will override the execute method to perform the desired operation for the call and return a JSON object to render in the HTTP response. For example, the following function queries a bank account for the given bank ID:

public class GetBankDetails extends JSONServlet {@Overrideprotected JSONObject execute(JSONRequest request)           throws JSONServletException, JSONException {   String id = request.getArgument("id");         if(id != null) {      Bank b = BanksRepository.instance()                                   .getBank(Integer.parseInt(id));               if(b != null) {         JSONObject bank = new JSONObject();            BankAccount chkAc = b.getCheckingAc();                     JSONObject checking = new JSONObject();         checking.put("number", chkAc.getNumber());         checking.put("balance", chkAc.getBalance());         checking.put("openedOn", chkAc.getOpenedOn());                     bank.put("checking", checking);                     return bank;      }   }         throw new JSONServletException("Unable to get bank details");   }   }

The Demo Application

The demo application retrieves data from the server. Figure 1 shows how the application looks at runtime.When a user selects a bank from the list, a request goes to the server to retrieve details pertaining to the selected bank. The details are abstracted in the JavaScript class BankDetails, and the method getBank gets called to get data from the server.

Figure 1. Application to Retrieve Data at Runtime: This application is configured to retrieve data from the server.
devx.yuiapp.BankDetails.prototype.getBank = function (id) {var onGetBankDetails = {   success : function (o) {   var bank = YAHOO.lang.JSON.parse(o.responseText);   main.bankDetails.bankIdTxt.set('value', id);   main.bankDetails.chkAcNoTxt.set('value', bank.checking.number);   main.bankDetails.chkBalTxt.set('value', bank.checking.balance);   main.bankDetails.chkAsOfDateTxt.set('value',                            bank.checking.openedOn);            main.bankDetails.createCDTable(id);   }      };   YAHOO.util.Connect.asyncRequest(   'GET',    'http://localhost:8080/pwds/GetBankDetails?id=' + id,    onGetBankDetails);   }

The YUI library Connect object is used to make the server call, and the response is passed in the callback method success in the onGetBankDetails object literal. The response text is parsed using the YUI JSON utility class’s parse method. The results are applied to the HTML elements using the reference to the fields.

Access to the fields are referenced from the main variable. This is done to gain access to the fields defined in the class BankDetails. The reference to the this variable doesn’t apply here because the method will be called in a different scope and the variable won’t be visible.

Saving Changes

Changes to the Balance field in the Checking account page are persisted to the server. The method save in the class BankDetails performs this operation.

Figure 2. Persisting Bank Data: The server-side AJAX function SaveBankDetails is called to persist the desired data.
devx.yuiapp.BankDetails.prototype.save = function () {   var args =       'id=' +       main.bankDetails.bankIdTxt.get('value') +       '&ac=checking&name=balance&value=' + main.bankDetails.chkBalTxt.get('value');      var onSave = {      success : function (o) {         alert('Saved');      }         };      YAHOO.util.Connect.asyncRequest(         'GET',          'http://localhost:8080/pwds/SaveBankDetails?' + args,          onSave);   }

The server-side AJAX function SaveBankDetails is called with the necessary arguments to persist the desired data (see Figure 2).

YUI DataTable Widget

The YUI DataTable widget is used for listing the certificate deposits associated to the Bank account holder. This widget provides out-of-the box support for both client- and server-side paging and sorting. Very minimal code is required to get this working. You need to define a placeholder in the HTML for the DataTable to appear.

The table is initialized when the user selects a bank from the list, and the method createCDTable in BankDetails gets called (see Listing 2). The definition of the table columns is defined, and the datasource is initialized and passed to the DataTable. The response schema indicates how the client should parse the response. The server implementation for this function call looks like Listing 3.

Sorting

The function arguments sort and dir are used for sorting. When the user clicks the column headers, the DataTable generates these arguments and passes them to the DataSource. They are then appended to the initial request and sent to the server.

The sorting is done on the server side for the account number column.

private List sort(List accounts, String dir) {   if("asc".equals(dir)) {      CDAccount.SORT_ASC = true;   } else {      CDAccount.SORT_ASC = false;   }         Collections.sort(accounts);         return accounts;}
Figure 3. Paging- and Sorting-enabled DataTable: The paging- and sorting-enabled DataTable looks like this.

Paging

At the point of initialization, the Paginator widget instance is passed to the DataTable. The Paginator widget generates arguments like startIndex and sends them to the server. The response should contain the meta-field totalRecords to make the widget render pagination links appropriately. The arguments recordsReturned, startIndex, pageSize, and totalRecords are all mandatory because the Paginator widget uses them.

The paging- and sorting-enabled DataTable looks like Figure 3.

A Complete Introduction to YUI

In this last article of a three-part series on the YUI library, you got a demonstration of the server-side interaction for fetching and persisting data back to the server using JSON. The first two covered JavaScript object-oriented programming and a few YUI widgets, respectively. Taken together, the series offers a good introduction.

The YUI documentation is a wealth of information for exploring the library further, particularly the API documentation. You will find the YUI library to be a feature-rich framework for developing rich user interfaces for your web applications.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: