Using JSON providers

According to the documentation (http://docs.jboss.org/resteasy/docs/2.0.0.GA/userguide/html/Built_in_JAXB_providers.html)
Resteasy supports different providers to create XML. JSON is particularly useful to return collections. It encloses lists, sets, or arrays of returned JAXB objects within a simple JSON array. For example:

For example, the following method is identical to getCollItems, except that it returns data using JSON provider:

@GET
@Path("items")
@Produces("application/json")
@Mapped
public ItemList  getJSONItems() {
  ArrayList list = new ArrayList();
  Item item1 = new Item("computer",2500);
  Item item2 = new Item("chair",100);
  Item item3 = new Item("table",200);

  list.add(item1);
  list.add(item2);
  list.add(item3);

  return new ItemList(list);
}  

This will return data using the following format:

{"listing":{"items":[{"description":{"$":"computer"},"price":{"$":"2500"}},{"description":{"$":"chair"},"price":{"$":"100"}},{"description":{"$":"table"},"price":{"$":"200"}}]}}    

You can use the following Ajax client to invoke the JSON service:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <script type="text/javascript">
function createXHR() {
    var request = false;
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (err2) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (err3) {
            try {
                request = new XMLHttpRequest();
            } catch (err1) {
                request = false;
            }
        }
    }
    return request;
}

function loadJSON(fname) {
    var xhr = createXHR();
    xhr.open("GET", fname, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status != 404) {
                var data = eval("(" + xhr.responseText + ")");
                document.getElementById("zone").innerHTML = "<h2>Items:</h2>";
                for (i = 0; i < 3; i++) {
                    document.getElementById("zone").innerHTML += data.listing.items[i].description + ', price <i>' + data.listing.items[i].price + "</i><br/>";
                }
            } else {
                document.getElementById("zone").innerHTML = fname + " not found";
            }
        }
    }
    xhr.send(null);
}
            <title>Ajax Get JSON Demo</title>
    </head>


    <body bgcolor="#FFFFFF">

        <p>
            <font size="+3">Ajax JSON/JAXB Demo</font>
        </p>
        <hr>
            <FORM name="ajax" method="POST" action="">

                <p>
                    <INPUT type="BUTTON" value=" Click to load the JSON file "
                        ONCLICK="loadJSON('resteasy/tutorial/items')">
                </p>

            </FORM>


            <div id="zone"></div>

    </body>
</html>       

   

Notice the core Javascript section, where data from JSON is extracted and placed in the "zone" DIV:

document.getElementById("zone").innerHTML += data.listing.items[i].description + ', price <i>' + data.listing.items[i].price + "</i><br/>";

Read the second part of this tutorial concerning RESTEasy web parameters handling

Running an older version of JBoss ?

Some installation steps might be required if you are running an older version of the application server, let's see them in detail.

JBoss 6/7

If you are going to run RESTEasy with JBoss 6/7 you don't have to download/install anything. The RESTEasy libraries are already bundled in the application server. Also the application server detects automatically the resources which are exported as Restful services.

All you have to do is inserting the correct web.xml namespaces:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

</web-app>

Older JBoss releases

If you have got any other JBoss AS release you have to perform a few basic steps for installing RESTEasy:

Step 1# Download Resteasy from the Repository

The first step is to download the latest Resteasy stable release from:
http://sourceforge.net/projects/resteasy/files/Resteasy%20JAX-RS/

Step 2# Add the following libraries to your Web application:

resteasy-libs

Step 3# Define listeners and bootstrap classes:

Add the following web.xml configuration:

<?xml version="1.0"?>
<!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>
    <display-name>RestEasy sample Web Application</display-name>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>sample.HelloWorldApplication</param-value>
        </init-param>

    </servlet>

    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

The org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap class is a ServletContextListener that configures an instance of an ResteasyProviderFactory and Registry.

Then, you need to set the parameter javax.ws.rs.core.Application with the singleton class which is used by your application to enlist all JAX-RS root resources and providers. Using JBoss 6-M4 and Higher this is not necessary as it's performed automatically by the application server when you deploy the .war

Finally you need to specify which url patterns need to be filtered by Resteasy. With the /* url-pattern all resources will be passed to resteasy servlet.

Step 4# Create the Singleton class

Now we need to add a special Singleton class to enlist all JAX-RS resources, as indicated by the javax.ws.rs.Application parameter.

package sample;

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

import sample.HelloWorld;

public class HelloWorldApplication extends Application
{
    private Set<Object> singletons = new HashSet();
    private Set<Class<?>> empty = new HashSet();

    public HelloWorldApplication() {
        // ADD YOUR RESTFUL RESOURCES HERE
        this.singletons.add(new HelloWorld());
    }

    public Set<Class<?>> getClasses()
    {
        return this.empty;
    }

    public Set<Object> getSingletons()
    {
        return this.singletons;
    }
}

This is your Application class which will enlist your RESTful services in the constructor. In our example, we will add the HelloWorld service.

Autoscanning of resources

If you prefer, you can let RESTeasy scan for your resources instead of adding the SingletonBean which installs your JAX-WS resources.  Just add the following configuration in your web.xml:

   <context-param>
      <param-name>resteasy.scan</param-name>
      <param-value>true</param-value>
   </context-param>
   <context-param>
      <param-name>resteasy.servlet.mapping.prefix</param-name>
      <param-value>/</param-value>
   </context-param>

0
0
0
s2smodern