Dojo JSON-RPC + Java May 6th, 2008 at 12:01 am by Kris Zyp
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 json.org’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 resp.getOutputStream().print(response.toString());
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 response.put("result",JSONObject.NULL); response.put("error",e.getMessage()); }
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:
<servlet> <servlet-name>JsonRpc</servlet-name> <servlet-class>com.sitepen.JsonRPC</servlet-class> </servlet> <servlet-mapping> <servlet-name>JsonRpc</servlet-name> <url-pattern>/jsonrpc/</url-pattern> </servlet-mapping>
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.
dojo.require("dojox.rpc.Service"); dojo.require("dojox.rpc.JsonRPC"); echoService = new dojox.rpc.Service({ envelope:"JSON-RPC-1.0", transport:"POST", target:"/jsonrpc/echo", services:{ sayHi:{ 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<String,Object> rpcTargets = new HashMap<String,Object>(); public static void registerRpcTarget(String path, Object target) { rpcTargets.put(path,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({ envelope:"JSON-RPC-1.0", transport:"POST", target:"/jsonrpc/myObject", services:{ foo:{ parameters:[{type:"string"}] // this is optional } } });
You can download the full source files: Echo.java, JsonRPC.java, 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.
Tags: json-rpc java rpc



Posted May 6th, 2008 at 2:36 pm
this link is break ..
can also be used with Dojo’s RPC services.
Posted May 6th, 2008 at 7:09 pm
can also be used with Dojo’s RPC services
these “Sorry, no posts matched your criteria.” words appear.
btw: There are not more document/information about dojo rpc. :)
Posted May 6th, 2008 at 7:33 pm
Sorry, it is future link to a post I haven’t published yet ;).
Posted May 8th, 2008 at 9:36 pm
Okss !!!
thanks
Posted June 25th, 2008 at 12:59 pm
JQuery’s version of the client
http://plugins.jquery.com/project/rpc
Server side some be the same.
Posted September 5th, 2008 at 3:53 am
I tried this code in my Web Application.
To correctly run correct the servlet mapping in Web.xml is
JsonRpc
/jsonrpc/*
Bye and thank’s!
Posted November 13th, 2008 at 10:14 am
It would be nice to have complete code to download. A sample jsp to go with the example would be nice.
I’m new to java, new to javascript, new to dojo, new to jabsorb. But as a developer if I had a working copy I would pick it up faster.
Posted June 17th, 2009 at 6:44 am
can anybody provide the jsp file to test this samples. thanks in advance
Posted June 17th, 2009 at 10:26 am
@ram: There were no JSPs used in this sample. It consists of a servlet and JavaScript code that interacts with it.