Dojo JSON-RPC + Java

By on May 6, 2008 12:01 am

Dojo supports JSON-RPC, which is an easy to use JSON-based remote method call format. JSON-RPC can be utilized for an interoperable approach to distributed computing and communicating with servers. We will look at an example of interacting with Java on the server and invoking a Java method from JavaScript using Dojo’s RPC services. We will be begin by demonstrating a simple JSON-RPC handler written in Java. First we will create a servlet and write a POST handler that will read the content from the request:

public class JsonRPC extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException, IOException {
         String content = streamToString(req.getInputStream());

Now we will use’s Java library to parse the JSON and extract the properties from the JSON object. A JSON-RPC object consists of three properties that define the invocation: method, params, and id. Here we extract these properties:

JSONObject rpcObject = new JSONObject(content);
	String methodName = rpcObject.getString("method");
	String id = rpcObject.getString("id");
	JSONArray paramsArray = rpcObject.getJSONArray("params");
	Object[] params = new Object[paramsArray.length()];
	for (int i = 0 ; i < paramsArray.length(); i++) {
		params[i] = paramsArray.get(i);

Now we can use these properties to execute a method on an object. If we already have a object that we want to use as the target of the RPC, we can use reflection to find the method and execute it:

for (Method method : target.getClass().getMethods()) {
	// we could use getMethod(methodName, paramTypes) here but
	// we would need to create a list of parameters types
	if (method.getName().equals(methodName)) {
		Object result = method.invoke(target, params);

Now that we have executed the method we can return the response to the client. The response object has three properties: id, result, and error. We can construct response using the JSON library:

response.put("id",id); // id from the request
	response.put("result",result); // result of the invocation
	response.put("error",JSONObject.NULL); // no error
	// send the response to the client

That is all that is necessary to write a class that can handle a successful JSON-RPC call. We could also wrap the execution in a try/catch and return an error result when an exception is thrown:

try {
	Object result = method.invoke(target, params);
} catch (Throwable e) {
	response.put("id",id); // id from the request

We will create very simple class to be the target of our JSON-RPC call:

public class Echo {
	public String sayHi(String from) {
		return "Hi " + from;

And we will create an instance of this class to be the target:

target = new Echo();

We can now register this servlet in our web.xml file:



Calling the Method with Dojo

On the client side, we can use an simple method description (SMD) object to describe our JSON-RPC service and Dojo will create the appropriate JavaScript methods.


echoService = new dojox.rpc.Service({
			parameters:[{type:"string"}] // this is optional

The echo now has a method sayHi that will execute the corresponding method on the Echo Java class. We can invoke the sayHi method with a normal JavaScript function call. The provided parameters will be included in the JSON-RPC call and used to invoke the method on the server. For example:

var deferred = echoService.sayHi("Kris");

This will execute sayHi with the an single argument of “Kris”. You may notice that the return value of the method is a Deferred object. This is because Dojo will execute the RPC asynchronously. When the RPC response is received the Deferred object will be fulfilled. In order to get the results of the call, you add a callback:

deferred.addCallback(function(result) {
    alert(result); // executed when the RPC is finished

When the RPC response is received from the server, the callback function will execute and the result will be alerted. Since we passed “Kris” to the sayHi method, the Java method will prepend the string with “Hi ” and return that result and the client should popup an alert with “Hi Kris”.

Multiple Target Objects

This example has a single Java object that is target of the RPC calls. However, it may be desirable to have multiple target Java objects. One approach for handling multiple objects is to create a mapping of URL paths to target objects. The JsonRpc servlet was intentionally declared to use a wildcard path (/jsonrpc/*) so it can handle multiple URL paths. We could create a rpc target map that maps these paths to objects:

static Map rpcTargets = new HashMap();
public static void registerRpcTarget(String path, Object target) {

Then we could lookup the target objects by URL path:

String targetPath = req.getPathInfo();
	Object target = rpcTargets.get(targetPath);

Now adding new target objects is simply a matter of registering the object in the map and creating a new SMD description for our object. Our echo object could be registered like this:

registerRpcTarget("/echo",new Echo());

If we created a new object we could register it:

registerRpcTarget("/myObject",new MyClass());

And on the client side we can create another service object from an SMD:

myObject = new dojox.rpc.Service({
			parameters:[{type:"string"}] // this is optional

You can download the full source files:,, jsonrpc.js. This is an example of using JSON-RPC directly in Java with minimal extra support, however, there are Java tools for automating JSON-RPC further, in particular jabsorb is another framework for using JSON-RPC within Java, which can also be used with Dojo’s RPC services.