RPC in Javascript using JSON-RPC-Java

Remote procedure call (RPC) in javascript is a great concept of creating rich web applications. First we will see some background about RPC using JavaScript Object Notation (JSON). See following quote from Wikipedia entry of JSON-RPC.
JSON-RPC is a remote procedure call protocol encoded in JSON. It is a very simple protocol (and very similar to XML-RPC), defining only a handful of data types and commands. In contrast to XML-RPC or SOAP, it allows for bidirectional communication between the service and the client, treating each more like peers and allowing peers to call one another or send notifications to one another. It also allows multiple calls to be sent to a peer which may be answered out of order. A JSON invocation can be carried on an HTTP request where the content-type is application/json. Besides using HTTP for transport, one may use TCP/IP sockets. Using sockets, one can create much more responsive web applications with JSON-RPC, compared to polling data from a service with JSON-RPC over HTTP.
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. For using JSON-RPC-Java in your code, you need to download following json-rpc-java-1.0.1.zip file and unzip it. http://oss.metaparadigm.com/jsonrpc/download.html The zip contains required jsonrpc-1.0.jar and jsonrpc.js files that we will use in our project. Once the JAR file is in classpath of your project, modify your WEB.XML (deployment descriptor) file and make an entry for JSONRPCServlet as follow.
<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>
Code language: HTML, XML (xml)
Note that JSONRPCServlet is a servlet class inside the jsonrpc-1.0.jar file. Also, we have mapped a URL /JSON-RPC with the servlet. Hence the servlet will be invoked by the container whenever this URL is called by the client. Also, do not forget in include the javascript file in your application.
Code language: HTML, XML (xml)
We will create a small webpage which will have two textboxes to enter numbers and a button which will call the RPC (call .sum() method on an object which resides in server) and send these two numbers to server. Server will do sum of these numbers and return the result back and the result will be displayed on webpage. Following is the content of the html page.
<title>JSON-RPC-Java Demo<br /> </title> <script type="text/javascript" src="js/jsonrpc.js"> </script> <script type="text/javascript"> function fnSum(form) { try { //Create a jsonrpc object for doing RPC. jsonrpc = new JSONRpcClient("JSON-RPC");</p> <p>// Call a Java method on the server result = jsonrpc.sumObject.sum(form.a.value, form.b.value); //Display the result alert(result);</p> <p>} catch(e) { alert(e.description); } } </script> <h1>JSON-RPC-JAVA</h1> <form> <input type="text" name="a"> <input type="text" name="b"> <input type="button" value="Sum"> </form>
Code language: HTML, XML (xml)
Note that in order to use JSON-RPC-Java, you need to set an object of com.metaparadigm.jsonrpc.JSONRPCBridge class in session. All the object that we will use in RPC from Client side needs to be registered into JSONRPCBridge’s object. JSONRPCBridge object can be written in session using jsp:useBean tag.
<jsp:usebean id="JSONRPCBridge" scope="session" class="com.metaparadigm.jsonrpc.JSONRPCBridge">
Code language: HTML, XML (xml)
We will use a business class called Sum which will do sum operation on the input and return the output. Following is the content of Sum class.
package net.viralpatel.jsonrpc; public class Sum { public Integer sum(Integer a, Integer b) { return a + b; } }
Code language: Java (java)
Thus we need to register an object of class Sum in JSONRPCBridge object in order to use it from javascript.
Sum sumObject = new Sum(); JSONRPCBridge.registerObject("sumObject", sumObject);
Code language: Java (java)
Doing RPC from javascript is easy now. All we need is an jsonrpc object that we get by doing jsonrpc = new JSONRpcClient(“JSON-RPC”);. Note that the argument passed inside the JSONRpcClient() is the URL that we mapped to JSONRPCServlet servlet. Once we get an object of jsonrpc, we can call remote methods by:
result = jsonrpc.sumObject.sum(form.a.value, form.b.value);
Code language: JavaScript (javascript)
Where sumObject is the name that we provided while registering Sum class to JSONRPCBridge. Following is the screenshot of the html page for user input. Following is the sum output that the server returned to webpage using json-rpc. Let me know your comments and suggestions on this tutorial. Update: Download Source code (war file, 79kb)

View Comments

  • Hi Viral,

    It is a nice article. It helped me understand the way JSON works.

    Do you know anything about the connection problem with the IE while using JSON RPC.

    After I submit my page the response is rendered but the browser hangs.

    It works fine in Firefox.

    Regards,
    Srinivas

    • Hi Srinivas, Thanks for the comment.
      I am unaware of the issue that you are facing. I remember when I created this example, it was working with IE too. Can you please elaborate your issue?

      • Hi Viral Patel ,
        I wana use json-rpc in my project, but I wonder "Can json-rpc support call client javascript method from server?". please help me. Thank you.

  • Thanks for the Tutorial,

    now I'm struggling with a call from a different domain. I figured out the URL but when I try open the connection I get following error

    "Cannot call method 'setUserRoutingParameter' of undefined"

    This is how my call looks like:

    jsonrpc.communicationClass.setUserRoutingParameter(
    resultCallbackParameter, jsonString);

    the communicationClass is registered as a bean on the server

    jsonrpc.communicationClass.setUserRoutingParameter(
    resultCallbackParameter, jsonString);

    Any ideas? Thanks a lot in advance!

  • I have Array return type so how can i pass this array into my action class(java servlet) .plz help me out

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

5 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

5 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

5 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

5 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago