JSONP with Jersey 2.0

1 minute read

As you build an API that is to be used by many parties you cannot escape the need for JSONP. JSONP is necessary when you need to provide cross domain support. In this article we will go through the steps necessary to support JSONP with Jersey 2.0.

The main difference between JSON and JSONP is that JSONP returns its datastructure wrapped in a piece of javascript which will be evaluated by the browser. The entire process is explained very well by a stack overflow user in this answer.

I just implemented an API which supports the JSONP protocol with the help of the Jersey 2.0 library, which is part of Glassfish 4. The internet is full of articles which implement JSONP using Jersey 1.x, which required you to wrap your object in another object, making it very hard to understand what is going on. Jersey 2.0 solves this by providing a new annotation, @JSONP.

@GET
@Path("/get")
@JSONP(queryParam="callback")
@Produces({"application/x-javascript"})
public TestResult getAllTestData(@QueryParam("callback") String callback) {
        TestResult result = new TestResult();

        // do many things here

        return result;
    }
}

To get the results you want you need to add both the JSONP annotation as well as adding the application/x-javascript type to the Produces annotation.

You can now call the remote service with the following jQuery javascript:

function getFeedList() {
    $.getJSON(serviceURL + 'get?callback=?', function(data) {
      // process the data
    });
}

The added callback parameter to the URL matches that of the QueryParam within the method in your Java class.

Image credit Joe Crawford (artlung)