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 the third party provide 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 an error.
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. 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>
@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);
}