Dojo + jabsorb

By on June 18, 2008 12:01 am

jabsorb is lightweight Ajax framework that uses JSON-RPC to communicate method calls from JavaScript to the Java server. Because of Dojo’s pluggable RPC and SMD capabilities, Dojo can easily be used to communicate method calls to the jabsorb server framework. Together, Dojo and jabsorb provide a very simple solution for integrating a UI with a Java back-end. Here we will see a quick demonstration of making a Java object available for remote calls from Dojo.

First, we build a Java class that will return a polite hello to whomever called it:

public class Hello {
   public String sayHello(String who)
   {
     return "hello " + who;
   }
}

Next, we expose an object instance of this class to the jabsorb framework in JSP:




<% JSONRPCBridge.registerObject("hello", hello); %>
...

Here we register an object called “hello” which is an instance of the Hello class. The jabsorb method naming convention defines that in order to call the sayHello method on the hello object, we call the method “hello.sayHello” using JSON-RPC. Now we create an RPC service in Dojo. We use an SMD definition to define the service that is available jabsorb:

dojo.require("dojox.rpc.Service");
dojo.require("dojox.rpc.JsonRPC");
var services = new dojox.rpc.Service({
	target:"/jabsorb-1.2/JSON-RPC",
	transport:"POST",
	envelope:"JSON-RPC-1.0",
	contentType:"application/json",
	services:{
		"hello.sayHello":{ // this is the method that we created in jabsorb
			returns:{"type":"string"},
			parameters:[{"type":"string"}]
		}
	}
});

We now have a services object that we can use to call the hello object. We can call the sayHello method on the server by calling the “hello.sayHello” method on the services object:

var deferred = services["hello.sayHello"]("Fred");
	deferred.addCallback(function(result) {
		alert(result);
	})

This calls the sayHello method with argument of “Fred”, which will return “hello Fred”. When the response is received from the server, the deferred object will be fulfilled, and the alert will give the friendly response.

In Dojo 1.2, we have provided “namespaced” service resolution, so this method would be available as services.hello.sayHello rather than services["hello.sayHello"]:

var deferred = services.hello.sayHello("Fred");

jabsorb is an easy to use server framework for handling remote method calls to Java objects using JSON-RPC. With Dojo’s pluggable service architecture, it is simple to connect Dojo to jabsorb to interact with existing Java code. jabsorb is one of a growing number of server frameworks that integrates well with Dojo.