Friday, June 8, 2007

How to use: JSON-RPC for Java

Why write about this?


Basically you can find all the information needed on JSON-RPC official site (http://oss.metaparadigm.com/jsonrpc/). But when I started to use the tutorial I realized that there is more information needed if you are a newbie using remoting technology. I'm not saying tutorial is not complete, If you follow the tutorial you will get the results expected, but you aren't going to understand what really happen and what you can modify to fit you project requirements. Actually I'll probably write more of these "how-to's" when I start to mix frameworks, API's etc; mixes that you probably will find in real world projects. So this little explanation about how to use JSON-RPC is the official tutorial but I'm adding what I'm think should be explained too and is not present in the original.


What is JSON-RPC for Java


JSON-RPC-Java is a key piece of Java web application middleware that allows JavaScript DHTML web applications to call remote methods in a Java Application Server without the need for page reloading (now referred to as AJAX). It enables a new breed of fast and highly dynamic enterprise Web 2.0 applications (using similar techniques to Gmail and Google Suggests).


From: http://oss.metaparadigm.com/jsonrpc/


Requirements


* ant 1.6 or later (to build)

* A Java Servlet container (such Apache Tomcat, the Tomcat service in JBoss, etc.).




Setup you environment:


* You will need to have configured Java Development Kit and your Servlet container

* Download JSON-RPC-Java at http://oss.metaparadigm.com/jsonrpc/download.html. The zip file will contain the JAR Library that will be part of your app library and a javascript file needed in your client side files.


Configuring web.xml

You need to configure the JSON-RPC servlet that will handle all the request from the client side. You just should add the following configuration into your web.xml
    
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-name>
<servlet-class>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-name>
<url-pattern>/JSON-RPC</url-pattern>
</servlet-mapping>
</web-app>

Registering your services.


When we talk about services we are talking about Java Object. Any object with public methods are candidate to be a service. In a multi-tier application the service layer will have the objects that we want to expose to the presentation layer.



For this tut, we are going create a POJO called test.jsonrpc.TestService (OMG what a original name!!!). This service will return a string with server date and will receive the format you need that date.



package test.jsonrpc;

public class TestService{
public String getHello(){
return "Hello friend!";
}
public String getRandomValue(int seed){
Integer value = Integer.valueOf( (int)( Math.random() * (double) seed) );
return value.toString();
}
}

In order to expose your services using JSON-RPC, you need to register them in somewhere. There are two ways to register your objects (as you will see at the end is the same ;) ).


In both case, you are going to use the JSONRPCBridge. The JSONRPCBridge holds references to exported objects and decodes and dispatches method calls to them. This means: if you need a object service (register or invoke) JSONRPCBridge is the man.


Registering objects via JSP:


Get a reference of JSONRPCBridge


...
<jsp:useBean id="JSONRPCBridge" scope="session"
class="com.metaparadigm.jsonrpc.JSONRPCBridge" />
...

Get a reference of the object you want to register


...
<jsp:useBean id="testService" scope="session"
class="test.jsonrpc.TestService" />
...

Registerint the object. The first parameter is the id what you want to register and the second parameter is the:


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

Registering via Servlet


Basically is the same thing, except you have to use pure java code:


  
...
// Find the JSONRPCBridge for this session or create one
// if it doesn't exist. Note the bridge must be named "JSONRPCBridge"
// in the HttpSession for the JSONRPCServlet to find it.
HttpSession session = request.getSession();
JSONRPCBridge json_bridge = null;
json_bridge = (JSONRPCBridge) session.getAttribute("JSONRPCBridge");
if(json_bridge == null) {
json_bridge = new JSONRPCBridge();
session.setAttribute("JSONRPCBridge", json_bridge);
}
...
json_bridge.registerObject("testService", new test.jsonrpc.TestService() );
...

For this tutorial we are going to use the JSP version for registering java objects.


Using your service on JavaScript:


Now that you have your service exposed through JSON-RPC is time to use it on a web page. We need to add the following code

on your web page.


 <script type="text/javascript" src="jsonrpc.js">

With the JSON-RPC distribution file, there is a javascript file called jsonrpc.js. You need to add it to your web project. In the above code, we are assuming the javascript file is at the same folder than the web page.



In order to invoke you service you need a JSON-RPC client on your JavaScript code. You get it creating a new JSONRpcClient.


 jsonrpc = new JSONRpcClient("JSON-RPC");

The following code creates two functions and creates a JSONRpcClient reference when the pages is loading.


 <script type="text/javascript" >
function onLoad()
{
jsonrpc = new JSONRpcClient("JSON-RPC");
}

function test1()
{
var text1 = document.getElementById("text");
var result = jsonrpc.testService.getHello();
alert("The server replied: " + result);
text1.value = result;
}

function test2()
{
var text2 = document.getElementById("text2");
var result = jsonrpc.testService.getRandomValue(5);
alert("The server replied: " + result);
text2.value = result;
}

</script>

When you want to invoke a service method you should use the following sentence:


jsonrpc.<registered name>.<methodname>( <parameters if apply> );

In our example, the methods test1 and test2 use the jsonrpc


 var result = jsonrpc.testService.getHello();
var result = jsonrpc.testService.getRandomValue(5);

 

JSON-RPC is really easy to use for a project:



  1. You just need to add the necesary libraries on your WEB-INF/lib folder

  2. Configure the JSON-RPC Servlet on web.xml

  3. Add the jsonrcp.js javascript file

  4. Register your Service using JSP or Servlet way

  5. Create a JSONRpcClient on JSP you want to invoke your service

  6. Use JSONRpcClient reference to invoke it.

0 comments: