Using JSONP with JAX-RS

Over the past few weeks I spent some time developing some REST services using JAX-RS, those services where invoked within jQuery scripts via Ajax. However, I’ve quickly fall into the same origin policy limitation.

The same origin policy prevents a document or script loaded from one origin (domain) from getting or setting properties of a document from another origin.

This is when JSONP came in help.
JSONP is designed to request data from a server in a different domain, basically it works by retrieving arbitrary JavaScript data instead of JSON data, the browser then send the name of the callback JavaScript function that will be fired once the content is returned.
Here is a detailed article if you want to know more about JSONP.

To demonstrate this concept let’s create a simple project that contains a REST service and a JavaScript client.

Server part

We’ll create a simple REST service using Jersey and Grizzly
For this, we use maven

mvn archetype:create -DgroupId=dev.nhachicha -DartifactId=restservice

Let’s added some dependency

		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-grizzly2</artifactId>
			<version>1.12</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-json</artifactId>
			<version>1.12</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-grizzly2-servlet</artifactId>
			<version>1.12</version>
		</dependency>

Now we can added a REST resource class (Service) this class define one method sayHello which take 2 arguments callback and  username

@Path("/rest")
public class Service {

	@GET
	@Produces("application/x-javascript")
	@Path("greeting/{username}")
	public JSONWithPadding sayHello (@QueryParam("callback") String callback,
								 @PathParam("username") String username) {
		Gson gson = new Gson();
		Message msg = new Message("Hello " + username);
		String json = gson.toJson(msg);
		return new JSONWithPadding(json,callback);
	}
}

It return a message using the given username and return the response as JSONP type with the given callback.
Since we use Grizzly as our embedded Webserver, we need to tell it where to find our service

ResourceConfig rc = new PackagesResourceConfig("dev.nhachicha");
			HttpServer server = GrizzlyServerFactory.createHttpServer(
							UriBuilder.fromUri("http://localhost/").port(9998).build(), rc);
			server.start();

To run the service

mvn exec:java

Our server is responding to the following URL http://localhost:9998/rest/greeting/

We’re done with the server part

Client part

The client part is a simple jQuery script that makes Ajax calls to our REST service
We specify JSONP as the expected data.

var url = 'http://localhost:9998/rest/greeting/' + $("#name").val();
	    $.ajax({
            type: "GET",
            url: url,
            data: {},
            async:true,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            success: function(data) {
            	showResponse(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert('error');
            },
            beforeSend: function (XMLHttpRequest) {
						//show loading
            },
            complete: function (XMLHttpRequest, textStatus) {
					//hide loading
            }
		});

The complete project is available on GitHub.

Resources

http://jersey.java.net/nonav/apidocs/1.5/jersey/com/sun/jersey/api/json/JSONWithPadding.html
http://persistentdesigns.com/wp/2009/08/jsonwithpadding-callbacks-json-xml-string-and-the-genericentity/
http://grizzly.java.net/nonav/docs/1.9/apidocs/com/sun/grizzly/http/servlet/ServletAdapter.html
http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/

Advertisements

About nhachicha

Android Developer, share experience about Java, System and Android
This entry was posted in Java and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s