Chapter 12
[ 345 ]
The @ResponseBody annotation will mean the result returned by the event action is
automatically placed in the HTTP response body. The @RequestMapping annotation
indicates that this action produces MediaType.APPLICATION_JSON_VALUE.
Combined, these annotations will ensure that the map that is returned is
converted to its corresponding JSON structure.
JSONP
If we were to serve the UI for this server from the same domain then this would be
adequate for most purposes. We will be building an embedded mobile client which
means that the UI will be served from the phone's own storage whereas the JSON
will be served from the Spring Boot app. Some browsers will enforce a same origin
policy and will not allow this. We circumvent this problem by using JSONP instead
of JSON.
JSONP is an alternative format to JSON whereby the returned value is a JavaScript
function call passing the JSON as a parameter. The snippet below shows a simple
piece of JSON and the JSONP equivalent:
//JSON
{ id: '123' }
//JSONP
callback({ id: '123' })
For a more detailed explanation of the JSONP mechanism, see http://json-p.org/.
All we need to know is how to generate this format in the response body.
AbstractJsonpResponseBodyAdvice is available in Spring 4.1. We extend this class
and annotate it with the @ControllerAdvice annotation. ControllerAdvice is a
mechanism in Spring for adding additional default functionality such as common
exception handlers to all controllers. In this case, we are adding JSONP capabilities to
all controllers:
@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback");
}
}