Calling JAX-RS Service Using AJAX Client

At the time of this writing, there is no standard way to generate AJAX client proxy for a JAX-RS RESTful service. You will find yourself writing a lot of code in the client side just to invoke these services. Several JAX-RS implementations provide their own proprietary client code generation solution. In this article, I will discuss how to generate a client if you are using RESTeasy. JBoss AS 7.1 uses RESTeasy by default which is what I used to test my work.

Let’s say that we have a very simple service resource class.

public class MyBean {
  public String getValue() {
    return "Some value";

First, register the code generation servlet in web.xml.

<servlet-name>RESTEasy JSAPI</servlet-name>
<servlet-name>RESTEasy JSAPI</servlet-name>

This binds the “/rest-api.js” path to the generated JavaScript. You can use any other path if you like.

In your HTML file, import the client side script.

<script type="text/javascript" src="rest-api.js"></script>

Note, “res-api.js” is the path to the JSAPIServlet as registered in web.xml.

The script defines a JavaScript object for every JAX-RS resource class by the same name. In our case, we will get a variable called MyBean. This JavaScript object has a method for each exposed method of the JAX-RS resource class. In our case, the name of the method will be getValue().

Let’s go ahead and code the rest of the HTML file.

  <script type="text/javascript" src="rest-api.js"></script>
  <script type="text/javascript">
  function doTest() {
    MyBean.getValue({$callback: onResult});
  function onResult(status, xhr, data) {
    console.log("Status is: " + status);
    if (status == 200)
        console.log("Do error handling");
<button onclick="doTest();">Test</button>

Basically, MyBean.getValue() method takes a parameter object. At minimum, we need to supply the callback method which is set using the $callback property. The callback method receives three input parameters:

  • The HTTP reply status. Use this to do error handling.
  • The XmlHttpRequest object used to make the AJAX call.
  • The actual reply data. If the response is a JSON document, then system parses it and gives you the JavaScript object. If the response is XML, then you get the Document object. Otherwise, you get the raw response data as is.

For more information, see the official doc on RESTeasy AJAX client programming.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.