I understand that custom filters can be used in earlier version of Spring MVC to implement JSONP. Additionally this example describes a method to implement JSONP in Spring MVC 3.1 by extending the MappingJacksonHttpMessageConverter
class and modifying the domain objects.
Is there a simpler (or conventional) method to address JSONP in Spring MVC 3.2 besides using the above methods? I did not see JSONP addressed at all in the Spring 3.2 documentation.
simpler way like this
@RequestMapping(value = "/jsonp", method = RequestMethod.GET)
@ResponseBody
public String jsonp(@RequestParam("c")String callBack) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
map.put("data", "<p>jsonp data<p>");
return objectMapper.writeValueAsString(new JSONPObject(callBack,map));
}
With spring 4.1 you can do this really simply with a @ControllerAdvice
https://spring.io/blog/2014/07/28/spring-framework-4-1-spring-mvc-improvements
You can simply use the spring-jsonp-support by Bhagya Silva as a dependency on your project.
https://github.com/bhagyas/spring-jsonp-support
More information is available on the README.md file.
I was looking for a simpler, OOB approach for JSONP approach (JSONP/CORS should be built-in IMO...not require any custom code)...never found any...but after reaching out with the Spring team, it turns out that JSONP is now supported OOB in 4.0.5 via MappingJacksonJsonView
and built-in support for CORS to follow later.
Here is the simplest way to handle this scenario
@GET
@Path("/jsonp")
@Produces("application/json")
public Response jsonp(@QueryParam("data") String json,
@QueryParam("callback") String callBack
@Context HttpServletRequest request) throws Exception {
String jsonResponse= "{ \"sttaus\" :\"some data\" }";
try{
.. // do your business logic
}catch(Exception e){ ... }
return Response.status(201).entity(callBack+"("+jsonResponse+")").build();
}