Enable Facebook, Twitter, Gmail and Yahoo sign in to your WordPress account with WordPress Social Sign On.
-
Recent Posts
Recent Comments
Archives
Categories
Meta
Enable Facebook, Twitter, Gmail and Yahoo sign in to your WordPress account with WordPress Social Sign On.
We learnt how AJAX works in previous articles; now we want to explore some techniques for using AJAX with Java technologies such as Java Server Pages (JSP), Java Server Faces (JSF) and others.
The most common way of using AJAX with Java technologies is to use JavaScript. You need to have AJAX functions, such as, creating an XMLHttpRequest object for your browser, then using the object requests for a JSP page or Servlet (in general, for an URL), get the response and use it in your JSP web pages. For this, what I usually do is, I create a JavaScript file with all these functions and include this .js file in my web pages using a <script> tag, and use the functions mentioned there. This is a very common technique of using AJAX with JSP, and this is almost the same for PHP. The following example will clear the concept more.
Problem: We need to get the server date time from a JSP page using AJAX.
Solution: First we will create a JSP web page that will output server data time like the one below.
<%=new java.util.Date()%>
Save the above line of code as index.jsp. The output will be as follows.

Now create the necessary JavaScript functions, like the one I typically use.
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == ‘get’ || method == ‘GET’){
http.open(method,url);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(“ajax_res”).innerHTML = response;
}
}
}
I usually save the above script as ajax.js. Add this JavaScript in your invoker JSP page (the page that will invoke the index.jsp to get the server date time) using AJAX.
The invoker JSP, caller.jsp –
<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8″%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<script src=”ajax.js”></script>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page using AJAX</title>
</head>
<body>
<a onclick=”sendRequest(‘GET’,'index.jsp’)” href=”#”>Server Date Time:</a>
<div id=”ajax_res”>Server Date Time will replace this text.</div>
</body>
</html>
This caller.jsp has a <div> element with the id=’ajax_res’. When I the user clicked the link ‘Server Date Time:’ as shown below, the JavaScript function sendRequest from ajax.js would be called to get the data from ‘index.jsp’ using HTTP GET method. The output of caller.jsp before clicking the link is

The output of caller.jsp after invoking the index.jsp using AJAX is

This way you can use AJAX with JSP for retrieving information from Database or from any file kept in the server, or can send the user information to server and get the response.
//break//
There is also an OpenSource project called AjaxTags. This AJAX Tag Library is a set of JSP tags that simplify the use of AJAX technology in Java Server Pages. This tag library offers following tags for common AJAX functionality.
This tag library relieves J2EE developers to write the necessary JavaScript to implement an AJAX-capable web form.
This implementation is a combination of Java classes and JavaScript source files. The Java code should be OS independent as there are no client side components. However, the Java is dependent on JDK 1.4+ and requires a Servlet container (like Tomcat) to run. The JavaScript should run in at least Firefox 1.0+ and Internet Explorer 5.0+.
To use AjaxTags tag library, first download it from http://ajaxtags.sourceforge.net/ and then copy the ajaxtags.jar into your WEB-INF/lib directory. Modify the web.xml for adding this tag library. Then add the dependency JavaScripts in your JSP pages. To learn more about this AjaxTags please visit the project homepage at http://ajaxtags.sourceforge.net/index.html.
There is another way of using AJAX with Java Server Faces user interface designs using Ajax4jsf. You can also use that. But the coolest AJAX tag library is jMaki. I’ll show you how to create a cool and nice with feature rich web page with jMaki and Netbeans 5.5 IDE in the next section.
According to the jMaki project team – jMaki is an Ajax framework that provides a lightweight model for creating JavaScript centric Ajax-enabled web applications using Java, PHP, and Phobos. To use jMaki with Netbeans IDE, first download the Netbeans module from https://ajax.dev.java.net/jmaki-plugin.html and install the module. Installation procedure is described nicely in this link.
After installing jMaki module you can create your web 2.0 applications with just some drags and drops. Some examples are here.
First, run the Netbeans IDE. Create a new project from File menu. Select web application. Select jMaki Ajax Framework. It will ask you to choose the CSS layout, select Standard one. It will create the banners, a side bar, home page link, sitemap link etc.
Here, you can see the JSP code at the left and the Palette at the right. There are a lots of jMaki widgets at the palette. jMaki has widgets for Flickr, Google, Yahoo and others. Using Flickr widgets, you can create captcha, word art, and search for images very easily. Let’s create an image search using jMaki Flickr widget. Just drag the widget from palette and drop in your JSP page. Now save the project, build and run. A browser will be opened as below.
Enter some va
lue in the edit box and click Search. It will get the images from Flickr using AJAX.
The JSP file looks like –
<%@ taglib prefix=”a” uri=”http://jmaki/v1.0/jsp” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html>
<head>
<link rel=”stylesheet” href=”jmaki-standard.css” type=”text/css”></link>
<title>Page Title</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
</head>
<body>
<div class=”outerBorder”>
<div class=”header”>
<div class=”banner”>Application Name</div>
<div class=”subheader”>
<div>
<a href=”mailto:feedback@youraddress”>Feedback</a> |
<a href=”#”>Site Map</a> |
<a href=”#”>Home</a>
</div>
</div> <!– sub-header –>
</div> <!– header –>
<div class=”main”>
<div class=”leftSidebar”>
Sidebar Content Here
</div> <!– leftSidebar –>
<div class=”content” style=”height:400px”>
<a:widget name=”flickr.search”
args=”{
topic:’flickrSearch’,
columns:3,
count:9
}”
service=”/xhp”/>
</div> <!– content –>
</div> <!– main –>
</div> <!– outerborder –>
</body>
</html>
//break//
Now let’s try another example. Pick the clock widget from the palette and drop it in your JSP code. Your code should look like this.
<div class=”content” style=”height:400px”>
<a:widget name=”dojo.clock” />
</div> <!– content –>

You can change the outlook of this widget also. To do this click within the code of the widget and then click jMaki button from Netbeans IDE as shown here.

Change the clockType value to Gray. The changed JSP would be like –
<div class=”content” style=”height:400px”>
<a:widget name=”dojo.clock” args=”{clockType:’gray’}”/>
</div>
Save the changes and refresh the browser. The output would be –

Here is a nice Yahoo slide bar for you.
<a:widget name=”yahoo.slider” />
Just add the above tag or drag it from palette. The output would be a nice simple slide bar.

Now add a Tabbed View widget from the palette in your code. The JSP code would be:
<div class=”content” style=”height:400px”>
<a:widget name=”yahoo.tabbedview”
value=”{tabs:[
{label:'My Tab', content: 'Some Content'},
{label:'My Tab 2', content: 'Tab 2 Content'}
]
}” />
</div> <!– content –>
You can change the labels from ‘My Tab’ to anything you need. You can also have as many tabs as required. The above code will create two tabs with labels and contents as described in the above code segment. Here is the output of this.

Isn’t jMaki cool?! There are lots of other cool widgets for you. Explore all the widgets, you will love jMaki definitely. You can also add Google Search or Yahoo Search by simply just dragging and dropping. Also you can add Google Maps very easily in your web pages. You can have menus, calendars, trees, editor, editable table and lots of other cool widgets in your web application very easily.
There is good news for PHP developers. That is they can also use jMaki with PHP. I tried to describe different ways and techniques here in this article to use AJAX with JSP. You choose which one better fits your need. Now, go try out these solutions and learn AJAX.
Building AJAX applications using Frameworks:
Any developer will typically create his Ajax application by writing XHTML pages and JavaScript code with his favorite integrated development environment (IDE) or even text editors. A number of different libraries and frameworks exist which allow programmers to use pre-designed JavaScript classes to implement otherwise time-consuming dynamic behaviors, such as drag-and-drop or sophisticated visual tree structures. Many are designed for developers who are already fairly well advanced in their JavaScript knowledge.
These simple methods are changing as powerful tools proliferate for Ajax developers. The GWT takes a different approach to Ajax than most toolkits.
The Google Web Toolkit’s Approach to Ajax:
Using the GWT framework, you can design and program your user interface using only the Java language. You then use the GWT’s command-line tools to check the syntax of the Java classes, and finally automatically generate the JavaScript for the application’s client-side. The design of the user interface is very similar to using Java’s Swing API.
Google Web Toolkit – An Overview
Google Web Toolkit (GWT) is an open source Java development framework that lets you escape the matrix of technologies that make writing AJAX applications so difficult and error prone. With GWT, you can develop and debug AJAX applications in the Java language using the Java development tools of your choice. When you deploy your application to production, the GWT compiler translates your Java application to browser-compliant JavaScript and HTML.
How GWT stands apart from other Frameworks?
GWT has the Java-to-JavaScript compiler to distill your application into a set of JavaScript and HTML files that you can serve with any web server. This approach makes the app cross browser compatible, making the feveloper’s life much easier.
GWT Architecture:
GWT has four major components: a Java-to-JavaScript compiler, a “hosted” web browser, and two Java class libraries (one the JAVA API and another GWT API)
Google Web Toolkit Features:
- Open Source
- Readymade, Dynamic, reusable UI components
- RPC
- Browser history management, debugging
- Browser compatible
- JUnit integration
- Internationalization
- Interoperability
- Fine-grained control
Debugging and Deploying GWT Applications:
GWT applications can be run in two modes:
• Hosted mode – In hosted mode, your application is run as Java bytecode within the Java Virtual Machine (JVM). You will typically spend most of your development time in hosted mode because running in the JVM means you can take advantage of Java’s debugging facilities and remain within an IDE like Eclipse.
• Web mode – In web mode, your application is run as pure JavaScript and HTML, compiled from your original Java source code with the GWT Java-to-JavaScript compiler. When you deploy your GWT applications to production, you deploy this JavaScript and HTML to your web servers, so end users will only see the web mode version of your application.
To support hosted mode, GWT ships with a special web browser with hooks into the JVM. See the GWT architecture diagram below for more information.
Getting Started:
Basic Download: Installing Google Web Toolkit
1. Install the Java SDK.If you don’t have a recent version of the Java SDK installed, download and install Sun Java Standard Edition SDK.
2. Download Google Web Toolkit.Download the Google Web Toolkit package for your operating system.
3. Unzip the Google Web Toolkit package.On Windows (or Windows Server), extract the files from gwt-windows-1.3.3.zip with a program like WinZip. On Mac and Linux, you can unpack the package with a command like
tar xvzf gwt-mac-1.3.3.tar.gz
Initial Setup under Various Environments:
The CLI scripts are designed to be run from a command-line window such as Terminal in Mac OS X. They include:
applicationCreator: This generates the skeleton directory structure for your application.
projectCreator : This script generates a project skeleton, as well as Ant build files or Eclipse projects, according to what the command line specifies.
i18nCreator : This creates some of the files required to use internationalized messages with GWT. The shortcut describes this application aspect in another section.
junitCreator : The script can be used to get you started using JUnit with GWT.
Kick Starting your First GWT Application:
GWT ships with a command line utility called applicationCreator that automatically generates all the files you’ll need in order to start a GWT project. It can also generate Eclipse project files and launch config files for easy hosted mode debugging, as described below.
We will use applicationCreator for our demo application Open a Terminal or CLI window and type:
applicationCreator -out /users/bruceperry/1ebooks/gwt -overwrite
com.parkerriver.gwt.intro.client.GwtAjax
This command uses the provided applicationCreator shell script to create a skeleton directory structure. We will use this structure to develop an Ajax application inside a file named GwtAjax.java. The first option with the applicationCreator command, -out, specifies the directory for your application or project (it defaults to the existing directory, the one where applicationCreator resides, which is the top-level directory when you unpack GWT).
The -overwrite option specifies that the command should overwrite any existing files. The final segment is the fully qualified name of the class where your application logic resides, usually representing the “entry point” class.
An entry point is the first screen the user interacts with in the Ajax application, such as a login window or a dashboard.
Based on the recommended GWT project structure, your main GWT application class should be in a subpackage client. You can create a new application called MyApplication with the command:
applicationCreator com.mycompany.client.MyApplication
The applicationCreator script will generate a number of files in src/com/mycompany/, including some basic “Hello, world” functionality in the class src/com/mycompany/client/MyApplication.java. The script also generates a hosted mode launch script called MyApplication-shell and a compilation script called MyApplication-compile.
//break//
GWT Directory Structure:
Whether you use the applicationCreator script or not, this is what your directory structure should look like. The client directory is where the Java class representing your user interface resides (such as the entry point class), and any of this class’s support classes.
The public directory contains an HTML file that has the same name as your client class, but with a different suffix: GwtAjax.html. This file is only necessary if you are not dynamically generating your entire user interface with JavaScript. The HTML file allows you to enclose the JavaScript associated with your application widgets within a bigger design. This is typically the way you will go, as the designers will be building the XHTML pages, which will point to the GWT-generated JavaScript. The dynamically generated user interface aspects are usually enclosed by XHTML div tags in these pages.
To run your newly created application in hosted mode, run the MyApplication-shell script:

Try editing the files src/com/mycompany/client/MyApplication.java and src/com/mycompany/public/MyApplication.html to see how it changes your application.
Creating an Application with Eclipse
GWT ships with a command line utility called applicationC
reator that automatically generates all the files you’ll need in order to start a GWT project. It can also generate Eclipse project files and launch config files for easy hosted mode debugging. To generate an Eclipse project for a new application, first use the projectCreator script to generate a shell Eclipse project for your application:
projectCreator -eclipse MyProject
Then generate your GWT application as described above, but with an additional -eclipse flag specifying the name of your Eclipse project:
applicationCreator -eclipse MyProject com.mycompany.client.MyApplication
When you’re done with these scripts, in addition to the MyApplication-shell and MyApplication-compile scripts, you should see .project, .classpath, and MyApplication.launch files in your current directory.
To open your project in Eclipse, launch Eclipse and click the File -> Import menu. Choose “Existing Projects into Workspace” in the first screen of the wizard, and enter the directory in which you genetrated the .project file in the next screen of the wizard. When you are complete, you should see your GWT project loaded into your Eclipse workspace:

Thinking beyond GWT:
It is not at all necessary for us to stick to the console level; so many IDEs are available out there. To quote a few
- Instantiations GWT Designer
- JetBrains GWT Studio
- GWT Widget Library
- Wirelexsoft VistaFei for GWT
Use of complex data types in Ajax programming is a tricky issue. In many scenarios we need to communicate between the clientand server via strings only.
In this article we discuss how ASP.NET AJAX handles complex data types. We wil use a web service for Ajax communication which will be exposed to client using Script Manager. Although complex data types can be handled using JSON objects, Script Manager internally JSON serialization for handling complex data types; so will we will not concern ourselves with JSON inthis article.
Let’s assume we have a Public class Employee as below.
public class Employee
{
public string name = string.Empty;
public string Address = string.Empty;
public string City = string.Empty;
public string zip = string.Empty;
public string [] phoneNumbers = null;
publicEmployee()
{
}
publicEmployee(string Name,stringAddress, string City, stringzip, string [] phoneNumber)
{
this.Address= Address;
this.City= City;
this.name= Name;
this.zip= zip;
this.phoneNumbers= new string[phoneNumber.Length];
this.phoneNumbers= phoneNumber;
}
public string setValues()
{
string_name = this.name;
string_Address = this.Address;
string_City = this.City;
string_zip = this.zip;
string[]_phoneNumbers = new string[this.phoneNumbers.Length];
_phoneNumbers = this.phoneNumbers;
return“SUCCESS”;
//Writeyour logic for setting values.
}
}
pan>
In above class the elements which need to be accessed in JavaScript are public – note we are not considering any function in a class.
We are going to expose a webservice to Script Manager for this article. So we also have a web service indemo code called “WebService.asmx”.
Following two namespaces arerequired to make a web service Ajax Enabled:
usingSystem.Web.Script.Services;
using System.Web.Script.Serialization;
Our web service class is as below:
[WebService(Namespace= "http://tempuri.org/")]
[WebServiceBinding(ConformsTo= WsiProfiles.BasicProfile1_1)]
[GenerateScriptType(typeof(Employee))]
[ScriptService]
public class WebService :System.Web.Services.WebService
{
public WebService()
{
//Uncommentthe following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string setValues(Employeeemp)
{
returnemp.setValues();
}
[WebMethod]
public Employee getDefaultData()
{
string[]PhnNum = { “123″,“222″,“234″};
&n
bsp; EmployeeEmp = new Employee(“Default Name”,“DefaultAddress”,“Default City”,“Default Zip”,PhnNum);
returnEmp;
}
}
Below are the two extra lines we have added above the WebService class, this is to indicate that the web service will be called from JavaScript, and creates the corresponding script object of class Employee.
[GenerateScriptType(typeof(Employee))]
[ScriptService]
In the Demo, Employee and WebService classesare added under namespace Demo and are in the same file “webservice.asmx”.
Our server side code ends here. Now we shall develop only client side code.
Our form tag is as follow
<form id=”form1″runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
<Scripts>
<asp:ScriptReference Path=”JScript.js” />
</Scripts>
<Services>
<asp:ServiceReference Path=”WebService.asmx” />
</Services>
</asp:ScriptManager>
<br />
Deal with ComplexData Types<br/>
<br />
<div>
<table border=”1″ cellpadding=”0″ cellspacing=”0″ style=”width: 730px; height: 74px” >
<tr>
<th align=”left”>Employee Name</th>
<th align=”left”>Address1</th>
<th align=”left”>City</th>
<th align=”left”>Pin Code</th>
<th align=”left”>Phone Number (seperate by ‘,’)</th>
</tr>
<tr>
<td align=”left” >
<input type=”text” id=”txtEmpName”/>
</td>
<td align=”left”>
<input type=”text” id=”txtAddress” />
</td>
<td align=”left”>
<input type=”text” id=”txtCity” />
</td>
<td align=”left”>
<input type=”text” id=”txtZipCode” />
</td>
<td align=”left”>
<input type=”text” id=”txtPhnNumber” />
</td>
</tr>
</table>
</div>
<br />
<input type=”button” id=”btnDefaultData” value=”Get Default Data” onclick=”_getDefaultData()”/>
<input type=”button” id=”btnCallServer” value=”Call Server” onclick=”_sendDataToServer();” />
</form>
In above code, we have used script manganer and registered our web service and JavaScript file.From here onwards we are goingto develop JavaScript
Calling of WebService methods using JavaScriptand script manager is very simple, we just need to use the simple namespace sequence.
e.g. If we want to call getDefaultData function of a webservice we simply need:
Demo.WebService.getDefaultData().
If we want to add a response handler we justneed to specify the function name in bracess like
> Demo.WebService.getDefaultData(OnSucceeded)
For the demo purpose our JavaScript contains threemain functions
· _getDefaultData() – This JavaScript function is used to call the web method get DefaultData. This Web Method returns default DataSet for the Employee class.
The JS function is as below
function_getDefaultData()
{
// This function gets default data from server.
Demo.WebService.getDefaultData(OnSucceeded)
}
· _sendDataToServer() – This JavaScript function is used to pass the clientside input to the server, or to the web method.
The JS function is as below
function_sendDataToServer()
{
// Create aninstance of the Server side employee class.
var obj = new Demo.Employee();
obj.name = window.document.getElementById(‘txtEmpName’).value;
obj.Address =window.document.getElementById(‘txtAddress’).value;
obj.City = window.document.getElementById(‘txtCity’).value;
obj.zip = window.document.getElementById(‘txtZipCode’).value;
obj.phoneNumbers =window.document.getElementById(‘txtPhnNumber’).value.split(‘,’);
// Call the Webservice method to send Client side values.
Demo.WebService.setValues(obj,OnSucceeded);
}
IN ABOVE FUNCTION CHECK THEWAY WE HAVE CREATED OBJECT OF AN EMPLOYEE CLASS. THIS EMPLOYEE CLASS EXISTS INC# CODE, BUT USING ASP.NET AJAX WE ARE ABLE TO CREATE AN INSTANCE ON CLIENTSIDE AS WELL.
· OnSucceeded(result,userContext,methodName) – This JavaScript function is used to handle the response from the server. The function is as below
// This is thecallback function that
// processes thecomplex type returned
// by the Webservice.
functionOnSucceeded(result,userContext, methodName)
{
if(methodName== “getDefaultData”)
{
window.document.getElementById(‘txtEmpName’).value = result.name;
window.document.getElementById(‘txtAddress’).value= result.Address;
window.document.getElementById(‘txtCity’).value = result.City;
window.document.getElementById(‘txtZipCode’).value = result.zip;
varphnNum = null;
for(var j = 0 ; j < result.phoneNumbers.length; j++)
{
if(j== 0) phnNum = result.phoneNumbers[j];
elsephnNum = phnNum + “,” +result.phoneNumbers[j]
}
window.document.getElementById(‘txtPhnNumber’).value = phnNum;
}
elsealert(result);
}
Refer the Demo code for better understanding of this code.
Synopsis: As the amount of logic implemented in javascript increases in response to demands in accessibility and client-side functionality, the opportunity for foot-shooting has increased exponentially. JDA is a nimble, kevlar-booted javascript message-passing kernel which manages communication between separate javascript modules and enforces that modularization. JDA stands for Javascript Dataflow Architecture. It is an open standard developed by MAYA Design Inc.
One would think that the Object Oriented revolution would have resulted in a sufficient modularization of software in itself, but recent years has seen the rise of several different types of “external” techniques to further separate parts of code from other parts, mostly for the sake of reuse, but also to release the programmers of the burden of tracking inter-connectivity of different parts of a system.
In the Java world, we have Spring as a very good example. Spring has many features, but one of the most obvious is automated configuration and ‘wiring’ of loosely coupled objects. What does this mean? It means that you can write a java program as a couple of different objects that can use each other, and which can accept initialization data, but nothing explicit about initialization or connections to other objects is ever mentioned in the code itself.
Instead, Spring relies on external configuration files which can initialize and ‘wire’ together java classes which themselves need not be aware of the Spring framework at all. This means that the programmers can focus more on the task at hand and leave interconnectedness and certain state issues to later wiring by Spring (or another container framework).
And more importantly, don’t we already have modular javascript? Take all those issues with prototype and mochikit way back when. They solved that with name spacing. Dojo had name-spacing since forever, and by having write dojo.byId(‘foo’) you make sure that no parts of your framework will ever barge in on someone elses.
Well, the kind of modularization we’re talking about here is really of another kind, but name-spacing is an important technique which solves the problem of using several frameworks at the same time. Mostly
But we already have widgets, you say. Again, taking dojo as an example, the widgets can be created programatically, or marked up as such in the page. They always have a DOM element to hang on, and they are both self-contained and hierarchical. Well, yes. Sure. But JDA is even more simple than widgets, though it uses similar techniques to mark things up.
The key to understand modular javascript in the JDA way is communication between modules. That’s what it’s all about. Most javascript programs are fairly small. Mostly this is due to a limited problem domain, but also to the expressiveness of modern scripting language. If you could take a JavaScript program and rewrite it in Java (for instance) it would generally be much longer. A good discussion on this can be found in Paul Bucheit’s blog (focusing mainly on APIs) and in CMSWire’s languages overview .
As Javascript programs grow in both size and complexity, spaghetti code tends to be a looming problem. This is of course not unique to javascript, and neither is the JDA pattern, which has been properly implemented in python, for instance (Probably dropping the leading ‘J’).
The basic assumption behind modularization of code in the first place is to protect the programmer from him or herself, by enforcing or encouraging separation of concerns and to create ‘natural’ borders between different parts of a system, the quick-fingered programmer receive cues where to put which new functionality.
In their thorough explanation of JDA, Seung Chan Lim and Peter Lucas defines JDA as “an ecosystem comprised of black box components operating within a JavaScript-based asynchronous message-passing environment”. By allowing for simple definitions of components, and a simple way to create multiple copies of the same, combined with a very simple message-passing abstraction, we get a compelling “workflow” where it costs little complexity to replace on of the components with another, or to make two or more connections from one components to other components, as needs for functionality in the application changes.
JDA uses the term ‘Infotron’ for a javascript module. A web page can contain any number of infotrons. Each infotron is an instance of a javascript ‘Blueprint’. That’s not a hand-waving term either, by the way. If you have loaded the JDA runtime in a page, you can define a blueprint like this;
The abov
e script defines a blueprint named “Simple Button”. You see that the first argument of the function BLUEPRINT in the JDA runtime is a unique identifier for the blueprint being defined. We could have written “xyzzy” instead and it would have worked, as long as no other blueprint were defined with that same UUID. General good practices, however recommend a proper UUID generated by the method of your choice.
//break//
A blueprint is a template of a component which you might put in your web page. When the BLUEPRINT function is called in JDA, the blueprint is defined, and can then be used multiple times with the page. In the above example, this means you can put ten different buttons on the page, all implementing the same blueprint. It is roughly analogous to the relationship between a class and an instance in true OO languages.
The second argument is a javascript property map with four named values; iterms, oterms, properties and name. The name is pretty obvious. The iterms and oterms stand for input and output terminals.
Input terminals are names which can be accessed externally and which have handler functions. In this first example, we have conveniently dispensed with any input terminals, saving them for later
Output terminals are, as you surely have understood by now, the counterparts of the input terminals. Their names are externally visible, and the JDA function postMessage(output_terminal, any_object); can be used to send a javascript object (or literal, whatever) to that specific terminal. An output terminal can then be wired together with an input terminal.
After that comes any number of methods defined inside the blueprint. JDA provides special methods, one being the _onInit, which (if present) is called as soon as any infotron based on the blueprint is instantiated in the page.
The _onInit method first declares a simple event function, and then creates a button element whose onclick event is then tied to that function. What happens in the event function is that the provided property “message” is sent on the output terminal “click_value_out” when the user clicks the button.
Note that this is a blueprint definition and it does not make anything show up in the page at all. For that to happen we must create an Infotron. Confused about Infotrons and Blueprints? Think like this; The blueprint is like prototype, the infotron is like calling element.puff(); You have to load prototype before you can use its goodies. But once you have, you can use them any number of times. Ok?
Let’s see a small example of an infotron using the above blueprint;
Not overly impressive, perhaps, but still a good start. Note that we are defining the infotron by using special tag properties. When JDA ‘boots’, it iterates all elements in the web page and registers all infotrons it finds. Since we might not have defined all blueprints we use prior to that (using the script tag in the head), we can also define the blueprint in the infotron definition. Note the names of the provided properties in the infotron definition, and that they are matched in the blueprint declaration.
We need more than one infotron to pass messages, though, so let’s define a simple blueprint which defines one input terminal and displays any message coming in inside a textarea;
Class.prototype.onMessage = function(msg)
{
this.debug(“Simple Show received message ‘”+msg+”‘”);
this.area.innerHTML = msg; // Ta-daa!
}
This blueprint in contrast to the first does not declare any output terminals, but has instead one input terminal. Note that the input terminal declaration contains some more information than the output terminal; The first item ‘message_in’ is the name of the input terminal, the ‘onMessage’ item is the name of the handler function, which is called as soon as a message is sent to the terminal, and the third property is the queue size of the terminal. If several messages are sent while the infotron is disabled for some reason, the are queued up to the number defined.
With some luck you now begin to see how these two blueprints fit together. But first we need to revise out earlier infotron definition snippet. We’ll add an infotron implementing the second blueprint, but also define a connection from the first to the second.
<div id=”showexample”
impl=”~197AA00D51114410d0A078238A52EF5F0“
script=”SimpleButton.js”>
</div>
Before we do anything else, just observe the austere beauty of these two infotrons. The javascript logic is locked up in separate files, which can be combined and pre-loaded by a ser
ver-side script if need be. Also, we are constraining the behavior of our scripts (not really, but we emphasize the encapsulation to the developer) inside the respective div elements. Further we are free to add CSS classes and styles which also separates logic from presentation.
JDA comes with a number of predefined blueprints, like a simple google map, form wrappers, a slideshow viewer, et.c. You also get a couple of convenience functions, like a debug version with copious output, and a debug output wrapper, which you can put in you pages for testing purposes, which redirects all debug output from both JDA itself and any ‘this.debug()’ statements you have in your blueprints to an area of your choice.
//break//
For small demos, it is sometimes convenient to just define the blueprints inside script statements in the page itself, and skimp on the script property in the infotron definitions.
A sample page with the above blueprints, and debugging enable would then look like this;
<script language=”javascript” src=”JsStar.debug.js”></script>
<script language=”javascript” src=”init_jsstar.js”></script>
<script>
BLUEPRINT(
“~027F54CD51114410dB7A77CB8A523E340″,
{
“iterms” : [],
“oterms” : ["click_value_out"],
“properties” : ["bname", "message"],
“name” : “Simple Button”
},
function (Class)
{
Class.prototype._onInit = function(props)
{
var self = this;
function _onClick(e)
{
self.postMessage(“click_value_out”, props["message"]); // postMessage is also provided to ‘this’ by JDA
}
this.button = document.createElement(“button”);
this.button.onclick = _onClick;
this.button.innerHTML = props["bname"]; // This is a named property which can be passed to us upon initialization
this.dom_node.appendChild(this.button); // this.dom_node is set by JDA to the element we are attached to
};
});
BLUEPRINT(
“~197AA00D51114410d0A078238A52EF5F0″,
{
“iterms” :
[
["message_in", "onMessage", 10]
],
“oterms” : [],
“properties” : [],
“name” : “Simple Show”
},
function (Class)
{
Class.prototype._onInit = function(props)
{
this.area = document.createElement(“textarea”);
this.dom_node.appendChild(this.area);
};
Class.prototype.onMessage = function(msg)
{
this.debug(“Simple Show received message ‘”+msg+”‘”);
this.area.innerHTML = msg; // Ta-daa!
}
});
window.onload = function(e)
{
__star.boot();
}
</script>
</head>
<body>
<div id=”buttonexample”
impl=”~027F54CD51114410dB7A77CB8A523E340″
properties = “‘bname’:'My Button’,'message’:'Foo!’”
connections=”‘click_value_out’ : [['showexample', 'message_in']]”>
</div>
<div id=”showexample”
impl=”~197AA00D51114410d0A078238A52EF5F0″>
</div>
<script language=”javascript” src=”debug.js”></script>
<div id=”debug” style=”position:absolute;bottom:20px;background-color:black;height:120px;width:100%;overflow:auto;”></div>
</body>
</html>
Here we see for the first time how JDA “boots”, by adding the __star.boot() call to window.onload. You framework of choice probably has a more generic onload handler for this event, but for our discussion, we stick to the basics.
If you want to see the demo in action, you can try it out here. If you want to download a zipped file with the demo, do so here.
Links to more information about JDA:
Introduction
. Whether we use Ajax or not, if it is a very long running process the browser may show a time-out error.
In case of ASP.NET AJAX if we use a script manager then we also have to define the time-out for the request which can be difficult in the scenario where we cannot predict how long a process will take to execute.
In this article we will discuss about this issue and how to use Ajax to handle long running process by using IAsyncResult and ICallbackEventHandler.
Web applications are based on a client-server architecture, so when the client hits the server the server will reply. If a long process is running on the server, then we may need some mechanism to determine when the long process is over. The long process can also delay the execution of other processes. To handle this issue we will use IAsyncResult . Using this interface and delegates we will able to run asyncronous processes on server side and invoke one method on server side while continuing with other tasks; once first method is complete it will automatically call another server method so that we can update some parameters say VAR1 and VAR2. And using ICallback we can check for VAR1 and VAR2, as soon as we get updated values, we will change status of long running method on client.
Using IAsyncResult, delegates and AsyncCallback
Classes which support asynchronous operations implement the IAsyncResult interface. IAsyncResult objects are passed back to methods invoked by AsyncCallback when an asynchronous operation completes. Classes which supports AsyncCallback in their methods return object of type IAsyncResult, for example - FileStream.BeginRead and FileStream.EndRead (these methods support AsyncCallback hence the return type is IAsyncResult). The same is true for BeginGetRequestStream method of WebRequest.
If we look at the parameters in these methods there is an AsyncCallback parameter which is the method that gets called once Async method is over. In our code this method is CallBackMethod.
On server side, we have used a delegate and on the button click event the function named DoSomething() gets called. This function take cares of the LongRunningMethod registration for the delegate and invoking of LongRunningMethod. While invoking LongRunningMethod we register the AsyncCallback method i.e. CallBackMethod.
CallBackMethod method can also be used to do other operations which may be dependent on the LongRunningMethod.
We will create a simple LongRunningMethod as follows:
private void LongRunningMethod(string name)
{
Thread.Sleep(60000 * 5);//This will run for 5 mins
}
We will now declare a delegate for above function , parameters for the delegate and the method should be same:
private delegate void LongRun(string name);
Implementation of the Async process on server side:
private IAsyncResult DoSomething()
{
LongRun Long = new LongRun(LongRunningMethod);
// Delegate will call LongRunningMethod
IAsyncResult ar = Long.BeginInvoke(“CHECK”,new AsyncCallback(CallBackMethod),null); //”CHECK” will go as function parameter to LongRunningMethod
return ar;
//Once LongRunningMethod is complete CallBackMethod method will be invoked.
}
private void CallBackMethod(IAsyncResult ar)
{
AsyncResult Result = (AsyncResult)ar;
LongRun Long = (LongRun)Result.AsyncDelegate;
Long.EndInvoke(Result);
}
Long.BeginInvoke in DoSomething will invoke LongRunningMethod method. While implenting this just check the parameters for BeginInvoke in .NET.
CallBackMethod gets called automatically after LongRunningMethod. CallBackMethod is used to end the invocation of the delegate.
On button click event we will call DoSomething function:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(“Long running process is started”);
Session["result"] = null;
IAsyncResult res = DoSomthing();
Session["result"] = res;
}
Now we will implement ICallbackEventHandler for cheking status of the process. If you are not familiar with ICallBack please refer to my introductory article Using ICallbackEventHandler in ASP.NET
Add following lines of code on server side:
public string GetCallbackResult()
{
if (res.IsCompleted)//Checking whether process is complete
{
IAsyncResult res = (IAsyncResult)Session["result"];
if (res.IsCompleted)
{
return “SUCCESS”;
}
}
return “FAIL”;
}
public void RaiseCallbackEvent(string args)
{
// Perform any operations here.
}
And on client side we will add two JavaScript function:
<form id=”form1″ runat=”server” >
<asp:Button ID=”Button1″ runat=”server” Text=”Button” OnClick=”Button1_Click” />
<div id=”Wait”>Click button to start long running process.</div>
<script language=”javascript”>
function CallServer()
{
window.document.getElementById(“Wait”).innerText = window.document.getElementById(“Wait”).innerText + “.”;
<%= ClientScript.GetCallbackEventReference(this,”", “ShowResult”, null) %>;
}
function ShowResult(eventArgument,context)
{
if(eventArgument == “SUCCESS”) {alert(‘Done’);};
else setTimeout(“CallServer()”,60000);//Priodic call to server.
}
</script>
</form>
After each 60sec we are invoking a callback to server which will check whether long running process is over or not. We can decide the callback period depending upon the long running process timing.
Please refer to the demo code for better understanding of the Article.
In the development of Ajax application many times we will encounter following issues.
Imagine the case of a financial data site (such as a stock market info site) with various regions of the page used for displaying data any taking user inputs. We may want to populate fill numerous div tags, textboxes and dropdown lists with real time data. If we loop the several requests and we will also have to check for timeout, if timeout occurs and no data is returned, then we will have to fire the same request again. It may end up that we have made 10 requests and 4-5 requests simply timeout because of network problems. If we dont loop then we will either get whole data or nothing (in which case there is only one more request to be made).
In this article we will discuss the XMLHTTPRequest object and JavaScript and develop a JavaScript class which can asychronously update multiple HTML elements. Also this class can be extended as per the requirements. I have used ASP.NET as the platform in this example but it does as the solution is just Javascript it can be applied to any web development platform.
Regarding classes in JavaScript, technically there is no ‘class’ in JavaScript but we can use a function as a class.
Consider the following code :
function testClass()
{
this.Msg = “Hello”;
this.showMsg = function()
{
alert(this.Msg);
}
}
var obj = new testClass();
obj.Msg = “HI”;
obj.showMsg();
In above script if we remove obj.Msg = “HI”; we will get an alert with text Hello.
We will now develop our JavaScript class step-by-step:
function AjaxClass()
{
this.Method = “GET”;//OR “POST”
this.Async = true; //OR false (asynchronous or synchronous call)
this.request = null;
this.init = function()
{
if (window.XMLHttpRequest) // if Mozilla, Safari etc
this.request = new XMLHttpRequest();
else if (window.ActiveXObject)
{ // if IE
try
{
this.request = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
this.request = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e){}
}
}
if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
//we will develope this.handleResponse function in step 3
this.request.open(this.Method, this.url , this.Async);
this.request.send(null);
}
}
}
Here we have created an XMLHTTPRequest object which is simply used to send a call to the server. The default method is GET (this.Method = “GET”) and calling type is Ascynchronous (this.Async = true)
For this one JSON (http://www.json.org/) object as follows.
this.JSONArray = { “Method” : “POST”, //Method type
“Async” : true, //Call type
“CallPage” : “CallPage.aspx”, //page or webservice
“Querystring” : “”, //Query string
“dependentType” : null,//[0,1,2,3] for isEdit
“isEdit”: [
{
"textBoxId" : null, //0 then this element
"dropDownId" : null, //1 then this element
&n
bsp; "default" : null, //2 then this element
"misc":null //3 then this element
}
]
};
In above script we can set the default values for all elements. We will use these values to set response from the server to textboxes,drop down lists,Div tags, td tags etc. Using “CallPage” : “CallPage.aspx” we can define default server page and while calling Ajax function we can change this value to web method or to any other web page.
As we will proceed in this article we will examine how to change all the above values and how can we use it to update multiple elements.Also we will see that how to extend the class.
In this step we will develop this.handleResponse function and in this function we will use the JSON object defined in Step 2. Whenever this.handleResponse function gets called script loses the focus of this. To keep track of this object we will asign it to some variable. i.e var self = this; // To lose of focus of the element
In this function we will be able to receive data from server. Once we receive the data we can manipulate it. This function will handle the responses from web services as well as from web pages. The web service always returns a response in the form of XML whereas the response from the webpage can be any format defined by web developer.
The function will be as follows:
var self = this; // To handle lose of focus
this.handleResponse = function()
{
if(self.request.readyState == 4 && self.request.status == 200)
{
if (window.ActiveXObject) // for IE
{
var doc=new ActiveXObject(“Microsoft.XMLDOM”);
doc.async=”false”;
doc.loadXML(self.request.responseText);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(self.request.responseText,”text/xml”);
}
try
{
var data = “”;
if(doc.documentElement) //Response from webservice
data = doc.documentElement.childNodes[0].nodeValue;
else data = self.request.responseText; //from web page
//data contains response text from the server
//At this point we have response from serve
//so here we will write our function to //manipulate the data. We will develop it in
//4th step.
}
catch(e) {}
}
}
In the the 1st step we had:
if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
this.request.open(this.Method, this.url , this.Async);
this.request.send(null);
}
We will now modify this so that we can directly use the JSON array which we defined in 2nd step:
if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
this.request.open(this.JSONArray.Method, this.url , this.JSONArray.Async);
this.request.send(null);
}
While developing Ajax applications we ned to be aware of the following issues regarding domains:
Thus our this.url = “http://myDomain/mysite/” + this.JSONArray.CallPage + this.JSONArray.Querystring;
e.g. “http://localhost/Demo/CallPage.aspx?”+this.JSONArray.Querystring;
Also whenever we want to call web methods like above example, we need to set following protocols under <webServices> in web.config file.
<webServices>
<protocols>
<add name=”HttpGet”/>
<add name=”HttpPost”/>
</protocols>
</webServices>
//break//
In
extCode> this.handleResponse (step 3) we have seen that we get response in the “data” variable in JavaScript.
So now we have response from the server we will add following logic:
switch(self.JSONArray.dependentType)
{
case 0:
PopulateControls(self.JSONArray.isEdit[0].textBoxId,data);
//simple call to JS function
break;
case 1:
PopulateControls(self.JSONArray.isEdit[0].dropDownId,data);
break;
}
self.JSONArray.isEdit[0].textBoxId will contain the id of the text box in which we need to update. And data is the response from the server. In our switch we have simply used the elements of JSON object developed in Step 2.
We will now focus on initiating a request and setting the elements of the JSON objects.
First simply create object of our AjaxClass().
var obj = new AjaxClass(); //Object creation
obj.JSONArray.Method = “GET”; //Setting Method
obj.JSONArray.isEdit[0].textBoxId=”txt1″;//Textboxid for response
obj.JSONArray.dependentType=0;//0->Textbox,1->drop downlist,
//2->tagId,3->Misc and so on
obj.init();//Initiate the AjaxCall
If obj.JSONArray.dependentType=1 then our switch case will not work for the textbox, but it will work for a dropdown list (check above switch case). This means we will have to set the dropdown in the JSON object:
obj.JSONArray.isEdit[0].dropDownId=”ddl1″;
In this way we can define our own set of HTML controls to be updated.
In the same way we can also change all the default settings in JSON object of that class.
e.g.
obj.JSONArray.Method = “GET”;
obj.JSONArray.CallPage = “Mywebservice/webMethod”;
obj.JSONArray.Querystring= “My querystring”;
For this URL will be : this.url = this.url + this.JSONArray.CallPage + this.JSONArray.Querystring ;
In case of a web service we will have to set the CallPage element as we did in the above example.
For multiple textboxes use: obj.JSONArray.isEdit[0].textBoxId=”txt1$txt2$txtn”;//$ is a delimiter
While sending data from the server send it with the same delimiter,in such a way when we split obj.JSONArray.isEdit[0].textBoxId and response data on $; we will receive data and the appropriate textBoxId.
Now that we have different types like “txtbox(es) + drop down list(s) + div” in such case we can use “misc” option of isEdit element of JSON object.
And we can define our PopulateControls function the way we want. For ASP.NET we could also integrate ICallback logic for large data transfers.
You can download the demo code here . This contains an ASP.NET project with the following files:
A lot more programmers and IT pro’s are studying for the Chartered Financial Analyst CFA Exam these days. The CFA Exam is a three stage exam commencing with CFA Level 1 Exam which is held in June and December each year.
CFA opens many horizons for developers as there is a constant requirement in the finance industry (despite the downturn) for systems development. In the last decade finance houses have started to look for developers with industry knowledge and the CFA designation is the best recognized qualification in finance. To qualify for the CFA designation an applicant is required to have a bachelors degree or at least four years of relevant experience.
In my previous article of Ajax enabled grid using ICallbackEventHandler I outline the creation of a grid with the following operations
In this article we will discuss editing the grid with the principal goal of doubleclicking on a grid cell to enable editing of that cell then edit the content of the cell and finally update server side data without refreshing the page.
The key advantages of this grid are as follows
The basic UI will contain one Gridview and one update button. We will bind data to grid on page load.
<div id=”Gridview”>
<asp:GridView EnableViewState=”false” runat=”server” id=”_grid” OnRowDataBound=”_grid_RowDataBound”>
</asp:GridView>
<span id =”ServerMsg”></span>
</div>
<br />
<input type=button value=”Update” onclick=”javascript: JSUpdateTable ();” />
<script language=”javascript”>
function UpdateGrid(args)
{
<%= ClientScript.GetCallbackEventReference(this,”args”, “ShowResult”, null) %>;
}
</script>
We have activated RowDataBound event of the grid.
public DataTable _sampleData
{
get {
DataTable dt = (DataTable) Session["DataTable"];
if(dt == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn(“Contact Name”,typeof(string)));
dt.Columns.Add(new DataColumn(“Company Name”, typeof(string)));
dt.Columns.Add(new DataColumn(“City”, typeof(string)));
dt.Columns.Add(new DataColumn(“Country”, typeof(string)));
dt.Rows.Add(new object[] { “Maria Anders” ,”Alfreds Futterkiste”,”Berlin”,”Germany”});
dt.Rows.Add(new object[] { “Ana Trujillo” ,”Emparedados y helados “,”México D.F.”,”Mexico”});
dt.Rows.Add(new object[] { “Antonio Moreno”, “Antonio Moreno Taquería”, “México D.F.”,”Mexico” });
Session["DataTable"] = dt;
}
return dt;
}
set
{
Session["DataTable"] = value;
}
}
We can write a function which will return a datatable, and the get property will simply return that table. We have used a session variable instead of viewstate to store the table; this is because we need to update data on the server side, if we use viewstate we would need to do post back of the page.
To bind this table to the grid we can simply set the datasource of the grid to the datatabe : _grid.DataSource = _sampleData;
And to set new data table we will add _sampleData = _tempTable;
Here _tempTable is the updated table after updating the grid on client side.
public void RaiseCallbackEvent(string eventArgument)
{
string[] args = eventArgument.Split(‘$’);
if (args[0] == “updateTable”) updateTable(args[1]);
}
public string GetCallbackResult()
{
return result;
}
The result is a global variable declared on the page.
We are following the same convention for RaiseCallbackEvent(string eventArgument) which we have used in my last article ( Ajax enabled grid using ICallbackEventHandler )
We can view a grid and and datatable as a two dimentional arrays with any cell being referenced by a row,column combination (i.e. row[i][j]).
As we have discussed earlier; we will look at the grid as a two dimentional array. Thus we will maintain unique id for each cell so that cell id will give the position of that cell in the datatable.
Here, understand that grid data is an exact copy of the datatable so row[i][j] in datatable will match with row[i][j] of grid.
Define _rowNumber as global variable for same page.
int _rowNumber = 0;
protected void _grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Attributes.Add(“ondblclick”, ”javascript:MakeCellEditable(this);”);
e.R
ow.Cells[i].Attributes.Add(“id”, _rowNumber + “_” + i);
}
_rowNumber += 1;
}
}
To make cell editable we have add:
e.Row.Cells[i].Attributes.Add(“ondblclick”,”javascript:MakeCellEditable(this);”);
MakeCellEditable(this) will write this JavaScript function in next step.
To identify each cell as unique cell and to mach it with corrosponding datatable entry, we will give id to each cell in such a way that it will follow row[i][j] structure.
i.e. e.Row.Cells[i].Attributes.Add(“id”, _rowNumber + “_” + i);
And we are increasing row number each time. Observe the way we have given id, we will get [i][j] position just by spliting the is on “_”.
function MakeCellEditable(obj)
{
if(!window.document.getElementById(obj.id + “_input”))
{
obj.innerHTML = “<input id=”+ obj.id + “_input” + ” type=text value=’” + obj.innerText + “‘/>”
}
window.document.getElementById(obj.id + “_input”).focus();
}
This function will convert the cell into text box and set focus in that text box. Check the way we have assinged theid to the text box (i.e.[i]_[j]_input obj is the cell)
//break//
Onclick of the Update button has a javascript function named UpdateTable() (refer to step 1). This function is listed below:
function JSUpdateTable()
{
var ddl = window.document.getElementById(‘Gridview’);
var ddl1 = ddl.getElementsByTagName(‘input’);
var data = “”;
for(i = 0 ; i < ddl1.length ; i++)
{
ddlId[i] = ddl1[i].id; //ddlId is a global array in JS we will use it in step 9
if(i == 0 ) data = ddl1[i].id + “|” + ddl1[i].value;
else data = data + “~” + ddl1[i].id + “|” + ddl1[i].value;
}
UpdateGrid(‘updateTable$’+data);
}
Recall step 3 where we defined RaiseCallbackEvent(string eventArgument) and used the updateTable function. On the updateTable is a server-side function which is responsible for updating the Datatable. The function will be as follows.
private void updateTable(string _data)
{
string[] _NewData = _data.Split(‘~’);
DataTable _tempTable = _sampleData;
for (int i = 0; i < _NewData.Length; i++)
{
string [] _changedTxt = _NewData[i].Split(‘|’);
string[] _rowCol = _changedTxt[0].Split(‘_’);
_tempTable.Rows[Convert.ToInt32(_rowCol[0])][Convert.ToInt32(_rowCol[1])] = _changedTxt[1];
}
_sampleData = _tempTable;
result = “SUCCESS”;
}
In step 7 we have seen the javascript function JSUpdateTable() and how we send updated data in the format of string.
For further understanding lets assume that we are sending data to the server and _data = “0_1_input|ABC~3_3_input|XYZ”. Now in the above function observe how we manipulate and parse _data.
result = “SUCCESS”; result is a global string.
After updating the DataTable on the server-side we will send result to client, and if result = “SUCCESS” we will know that the datatable has been updated successfully.
The GetCallbackResult() function (ref. step 3) will send result string to client.
function UpdateGrid(args)
{
<%= ClientScript.GetCallbackEventReference(this,”args”, “ShowResult”, null) %>;
}
(Please reffer my previouse AJAX Grid article for more details on this function)
ShowResult JavaScript function will get called automatically after the GetCallbackResult(), so now we will write this function.
var ddlId = new Array();//Elements are added in step 7
// This array contain ids of textboxes
function ShowResult(eventArgument ,context)
{
formObj = window.document;
if(eventArgument == “SUCCESS”)
{
for(j = 0 ; j < ddlId.length ; j++)
{
var ids = ddlId[j].split(“_”);
formObj.getElementById(ids[0] + “_” + ids[1]).innerHTML = formObj.getElementById(ddlId[j]).value;
}
document.getElementById(‘ServerMsg’).innerText = “Data has been updated Successfully…”;
}
}
The above function is used only remove editable cells (i.e. to remove textboxes and to indicate that the server data has been updated)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_grid.DataSource = _sampleData;
_grid.DataBind();
}
}
Further Enhancements
For editing the grid some points need to be considered. We have discussed only about using text boxes for editing but we could also use a dropdownlist or other controls.
If we are using paging and sorting updating a row in the datatable causes a problem for cell referencing. In this case we can add a column to the datatable which corresponds to table row, so if we sort the table and can still maintain the row number (i.e [i] in row[i][j] ). This column will be hidden in the grid so that we can use it for adding and deleting the the data as well.
Code
The full code can be downloaded here
The code contains two aspx pages
Services in GWT
Google Web Toolkit is a Web Application Framework dealing with Servers and Clients. When a Server is required to do some processing in a web-app Services must be used. A service is used to invoke server-side code from the client (and vice-versa occasionally).
In GWT the Client side code pages run more like an application within the Client (Browser), so requesting the HTML pages from the Server is not necessary. But in common with all Server-Client Architectures, even GWT needs to contact the Server as they execute, this is carried out by Remote Procedure Calls (RPC).
What is RPC?
RPC is a powerful technique for constructing distributed, client-server based applications. It is based on extending the notion of conventional or local procedure, so that the called procedure need not exist in the same address space as the calling procedure. GWT automatically generates most of the classes required for RPC.
Services: Creation and Implementation.
Before getting into RPC, we will have a look at relationships between various classes and interfaces that we are creating for a service. With GWT Framework classes we create certain classes and interfaces for THE RPC Service.
Remote Procedure Call – In Detail
Client Creation:
To start with, we will create a client side code, by creating an Interface that extends the RemoteService Interface
public interface MyService extends RemoteService {
public String myMethod(String s);
}
Any implementation of this Service must extend the RemoteServiceServlet and should Implement this Service Interface:
public class MyServiceImpl extends RemoteServiceServlet implements MyService {
public String myMethod(String s) {
// Do something interesting with ‘s’ here on the server.
return s;
}
}
Call Progress:
Now we need an Asynchronous Interface based on our Service Interface:
interface MyServiceAsync {
public void myMethod(String s, AsyncCallback callback);
}
If we are using Asynchronous method calls, then we have to have callback object that can serve as a messenger to indicate when the call is completed.
Asynchronous methods are always void, only the callback object is used for communication to the caller.
A service Interface and its Asynchronous counterpart have one simple relationship. The Asynchronous method must be in the same package as the Service Interface. If a service interface is called com.example.cal.client.AjaxMattersService, then the asynchronous interface must be called com.example.cal.client.AjaxMattersServiceAsync.
For each method in the Service Interface,
public ReturnType methodName(ParamType1 param1, ParamType2 param2);
the Asynchronous Interface must look something like this
public void methodName(ParamType1 param1, ParamType2 param2, AsyncCallback callback);
In order to respond to client requests, the service ultimately needs to perform some processing. Such server-side processing occurs in the service implementation. A service implementation must extend RemoteServiceServlet and must implement the associated service interface. One important thing that to be noted here is that, the service implementation does not implement the asynchronous version of the service interface. to simplify matters we can say that every service implementation is ultimately a servlet, but rather than extending HttpServlet, it extends RemoteServiceServlet instead.
//break//
How a Call is made?
The steps are pretty simple:
1. Instantiate the service interface using GWT.create().
2. Specify a service entry point URL for the service proxy using ServiceDefTarget.
3. Create an asynchronous callback object to be notified when the RPC has completed and make a call.
Serialization in GWT:
GWT tries really hard to make serialization as painless and as easy as possible, so while the rules regarding serialization are subtle, in practice the behavior becomes intuitive very quickly. That is the actually goal of GWT since it is involved in Web Applications. Serialization provides a simple and robust way to make object persistent and in case of RPCs, serialization plays a viral role. There are some conditions which GWT enforces for a type to be serializable and for it to be used in Service Interface.
Java objects and primitive types that can be serialized and transmitted via the GWT-RPC mechanism:
| Java primitive types | boolean, byte, char, double, float, int, long, short |
| Java primitive wrapper types | Boolean, Byte, Character, Double, Float, Integer, Long, Short |
| Subset Java objects | Only ArrayList, Date, HashMap, HashSet, String, Vector |
| User defined classes | Any class that implements IsSerializable |
| Arrays | An array of any of the serializable types |
Serializable User-defined Classes
A User Defined Class is said to be Serializable if it implements the IsSerializable interface. This is an interface that is part of the GWT library, and is used to signify that a class may be serialized via reflection techniques. This serves the same purpose as Java’s own java.io.Serializable interface, but is specific to GWT applications.
All non-transient fields in the class are serializable; by ‘
non-transient field’ we mean any field not using the transient modifier. GWT will also not serialize fields that have been marked as final, but don’t rely on this and be sure to mark all final fields as transient. The class has a zero argument constructor or no constructor at all.
Polymorphism
In terms of optimizations for the GWT compiler, it is good to be as specific as possible when specifying the types of your fields in the data object. For example it is common practice to specify java.util.List as a type instead of either ArrayList or Vector. The benefit of using a generalized type is that it allows you to change the underlying implementation without changing the type declaration. The problem is that when you generalize the type it is harder for the GWT compiler to optimize the code, and you often end up with larger JavaScript files. So the rule of thumb it to try to be as specific as possible in your typing.
Arguments
By Arguments, here we mean the Type Arguments. Suppose if we have a case where we use collections, we can’t be very specific, in that case the conflict arises. In order to solve this, GWT provides an annotation that allows us to let the compiler know what types of objects are being used in the collection. As this is not a Java 5 annotation, we have to provide an inside Java Comment.
/**
* @gwt.typeArgs <java.lang.String>
*/
private ArrayList listOfWords;
/**
* @gwt.typeArgs <java.util.Date>
*/
private Vector listOfDates;
We can also implement this for return types and parameters.
Exception Handling in GWT
Remote Procedure Calls open up the possibilities of errors and exceptions. Errors may be due to various issues such as Network error, Server related issues, Server-Client call transactions etc. GWT allows us to handle exceptions easily and efficiently. Any RPC related exception can be categorized into two types.
Checked Exceptions
Unexpected Exceptions
Common or Checked Exceptions
When a Service interface method is implemented there are many possibilities of exceptions being thrown and in order to handle that throw, declarations are added. The throw indicates that an exception may be thrown back during the implementation. AsyncCallback.onFailure(Throwable)is the primary interface a caller must implement to receive a response from a remote procedure call. If an RPC is successful, then onSuccess(Object) is called, otherwise onFailure(Throwable) is called. The asynchronous method always takes an AsyncCallback as its last parameter.
e.g.: Animal[] getAnimals(String databaseName) throws AnimalException, DbException;
Its asynchronous counterpart method is declared as:
void getAnimals(String databaseName, AsyncCallback callback);
Note that the throws declaration is not repeated in the Async version.
A typical AsyncCallback call might look like this:
service.getAnimals(dbName, new AsyncCallback() {
public void onSuccess(Object result) {
// Downcasting to the known return type.
Animal[] animals = (Animal[]) result;
controller.processAnimals(animals);
}
public void onFailure(Throwable caught) {
try {
throw caught;
} catch (InvocationException e) {
// Call terminated in a adhoc way
} catch (AnimalException e) {
// one of the ‘throws’ from the original method
} catch (DbException e) {
// one of the ‘throws’ from the original method
} catch (Throwable e) {
// last resort — a very unexpected exception
}
}
});
Ad-hoc Exceptions
If an Exception occurs ‘ad-hoc’ then it is termed an Unchecked Exception. There are many reasons why such exceptions might occur, they will be mainly due to machine and server related issues. Network breakdown, DNS error, HTTP process error etc.
An InvocationException is passed to the implementation of AsyncCallback.onFailure (Throwable). This class is called InvocationException because the problem was with the invocation attempt itself rather than with the service implementation. A NullPointerException might also lead to this, since that is ad-hoc.
There are two types of InvocationException:
| InvocationException(String) | Constructs an exception with the given description. |
| InvocationException(String, Throwable) | Constructs an exception with the given description and cause. |
GWT also allows us to implement almost all types of exceptions that are in Java.
Asynchronous Calls
An asynchronous call comes into play when we need parallelism in our applications.
For example if we have a page which contains a huge table containing many widgets and we need to fetch data from the Server for the table and at the same time as we need to construct all the widgets that are required building the table itself is time consuming and fetching the data adds to the load. If we implement Asynchronous calls by the time the table is constructed with widgets, the data can be fetched from the Server Asynchronously, this will reduce the load time and at the same time double the efficiency.
In case of Asynchronous calls, a common problem is blocking, but this can be managed with the concept of Inner classes.
RPC Example:
1. Create a new Eclipse GWT project named MyFirstRPC using the projectCreator and applicationCreator. Set the name of the application class to com.test.MyFirstRPC.client.MyFirstRPC.
2. If you are comfortable you can build the Project as it is or you can use any standard IDE like Eclipse.
3. Create a Java file and name it as NumsService.java in the com.test.MyFirstRPC.client package.
Define a NumsService interface with one method that verifies if a number is an even. It takes an integer as a parameter and returns a Boolean value upon verification:
public interface NumsService extends RemoteService
{
public boolean isEven(int numberToVerify);
}
4.Create a new Java file named NumsServiceAsync.java in the com.test.MyFirstRPC.client package. Define a NumsServiceAsync interface:
public interface NumsServiceAsync
{
public void isEven(inr numberToVerify, AsyncCallbackcallback);
}
5.Create a new Java file, named NumsServiceImpl.java in the com.test.MyFirstRPC.
server package. Define a NumsServiceImpl class that extends RemoteServiceServlet and implements the previously created NumsService interface. Add functionality to this class to verify if the provided number is an even number.
public class NumsServiceImpl extends RemoteServiceServlet
implements NumsService
{
private static final long serialVersionUID = -8620968747002510678L;
public boolean isEven(int numberToVerify)
{
boolean numIs = false;
if ( (numberToVerify%2)==0)
{
numIs = true;
break;
}
return numIs;
}
}
//break//
6. Create the client in a new file named NumsClient.java in the com.test.MyFirstRPC.client package that extends the EntryPoint class.
public class NumsClient implements EntryPoint
{
}
7. Add an onModuleLoad() method to this new class, and create a text box.
public void onModuleLoad()
{
final TextBox IsEvenTxt = new TextBox();
}
8. Instantiate the NumsService and store it in a variable in the onModuleLoad()method.
final NumsServiceAsync NumsService = (NumsServiceAsync) GWT
GWT.create(NumsService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) NumsService;
endpoint.setServiceEntryPoint(GWT.getModuleBaseURL()+”Nums”);
9. Create a new button, and add an event handler to listen for clicks on the button. In the handler, invoke the NumsService using the text typed into the text box as the input parameter to the service. Display the result in an alert dialog.
final Button checkNum=new Button(“Is this an Even number?”,
new ClickListener())
{
public void onClick(Widget sender)
{
AsyncCallback callback = new AsyncCallback()
{
public void onSuccess(Object result)
{
if(((Boolean) result).booleanValue())
{
Window.alert(“Yes, “+ IsEvenTxt.getText()
+ “‘ is a Even number.”);
}
else
{
Window.alert(“No, “+ IsEvenTxt.getText()
+ “‘ is not a Even number.”);
}
}
public void onFailure(Throwable caught)
{
Window.alert(“Error while calling the Nums
Service.”);
}
};
NumsService.isIsEvenTxt(Integer
parseInt(IsEvenTxt.getText()), callback);
}
});
10. Add the following entry to the application’s module.xml file in order for the client to find this service.
<servlet path=”/Nums” class=
“com.test.MyFirstRPC.server.NumsServiceImpl”/>
When you execute the app, you will get the result like this
Conclusion:
Google Web Toolkit has made RPC really simple and at the same time with the implementation of Asynchronous Calls the transactions occurs parallely and dynamically giving the User a complete AJAX experience and the developer a easy life to architect the application.