One of the current trends in web applications is communicating with the content and functionality from two different sources. For example, features such as embedding adding maps, videos and playlists, comments of third party provides into your own application.

Browsers security restriction imposes the cross domain web Service calls using Ajax.  All the modern bowsers by default do not support cross domain Ajax calls. If you do so, it will end up with the following error:

XMLHttpRequest cannot load URL. Origin http://yourwebserver.com is not allowed by Access-Control-Allow-Origin.

-Advertisement-

Visit the below link for more details on browser security policy: Same-origin policy. The solution to the above problem is JSONP.

What is JSONP?

JSONP (JSON with Padding) is a technique used by web developers to overcome the cross-domain restrictions imposed by browsers to allow data to be retrieved from systems other than the one the page was served by.

Support JSONP in Spring MVC 4.2

Since Spring version 4.2 release, the JSONP is inbuilt to  Spring framework. In order to enable JSONP support for @ResponseBody and ResponseEntity methods, declare an @ControllerAdvice bean that extends AbstractJsonpResponseBodyAdvice as shown below where the constructor argument indicates the JSONP query parameter name(s):

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

@ControllerAdvice 
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {

    public JsonpAdvice() {
        super("callback");
    }

}

With such @ControllerAdvice bean registered, it will be possible to request the JSON web service from another domain using a <script /> tag.

Let us consider the following bean

public class Post {
	private int id;
	private String title;
	private String body;
}

The above bean can be accessed via JSONP using the URL as http://localhost:8080/myapp/post?callback=postCallback, and it In this example, the received JSONP payload would be:

postCallback({
	id: 11,
	title: "Post title",
	body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ",
})

If you want to access it form another domain, we can use it as

<script src="http://localhost:8080/myapp/post?callback=postCallback" type="application/javascript"> 
</script>

JSONP with @ResponseBody and ResponseEntity

Now find a controller in which we have created methods that will return @ResponseBody and ResponseEntity.

@RequestMapping(value = "/post", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Post> embedSnippet(HttpServletResponse response) {
	Post post = new Post();
	post.setId(11);
	post.setTitle("Post title");
	post.setBody("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");
	
	return ResponseEntity.accepted().body(post);
}

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.

Comments are closed here.