0

Building a RESTful Service that returns JSONP using the Spring Framework

This is not a duplicate of my previous blog entry of Building a RESTful Service that returns JSON using the Spring Framework. In this blog post I’m going to show how you can return JSONP so that you can call your REST APIs directly from your Javascript functions. If you are wondering why you can’t just simply use your existing REST APIs with Javascript then you will want to read up on JSONP. The basic idea is that the caller will pass a “callback” parameter to your API which is essentially a JSON function name. You then have to wrap your return within open and close parens and the callback function name so that it makes the Javascript runtime environment get tricked into thinking that it is running a local JS function.

So Here’s some code that will do this. Building on the SimpleRestController from the previous blog posts:

@RequestMapping(value = "/simple/pojo_hashmap/jsonp", method = RequestMethod.GET)
public ResponseEntity handleSimpleJsonp(@RequestParam("callback") String inCallback) {

	StringBuffer theStringBuffer = new StringBuffer();
        HashMap theHashMap = new HashMap();

	theHashMap.put("Great Coffee", "Barefoot");
	theHashMap.put("Bad Coffee", "Starbucks");

	// add the callback function name and open paren
	theStringBuffer.append(inCallback);
	theStringBuffer.append("(");

	// serialize the POJO to JSON
	String theResponseString = serializeToJson(theHashMap); 

	// add the JSON string and close parens
	theStringBuffer.append(theResponseString);
	theStringBuffer.append(")");

	return new ResponseEntity(theStringBuffer.toString(), new HttpHeaders(), HttpStatus.OK);
}

private String serializeToJson(Object theObject) {

	String theJsonString = null;

	try {
		ObjectMapper theObjectMapper = new ObjectMapper();
		ByteArrayOutputStream theJsonOutputStream = new ByteArrayOutputStream();
		theObjectMapper.writeValue(theJsonOutputStream, theObject);

		theJsonString = theJsonOutputStream.toString("UTF-8");
	} catch (Exception theException) {
	        theException.printStackTrace();
        }

     return theJsonString;

}

Here we are including a callback input parameter to our controller method handleSimpleJsonP(). This is the Javascript function name that we will have to wrap the return with. In the previous blog post we didn’t have to worry about any callbacks so we could just return the POJO right away however now we need the intermediary step of getting the serialized version of the POJO. We accomplish this with the new serializeToJson() method that we added. We just pass it in a POJO and get back a UTF-8 JSON String. Now we can just wrap this string with the callback and the open and close parens and return it. Thats all there is to it and now you can have your Javascript functions making direct API calls into your RESTful Service.

Now when you call your service with a call like:

http://localhost:8080/simple/pojo_hashmap/jsonp?callback=getCoffeeAdvice

You will get a result like this:

getCoffeeAdvice({"Great Coffee":"Barefoot","Bad Coffee":"Starbucks"})

Leave a Reply

Copyright © 2009-2025 Fouzi Husaini's Blog All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.