Implementing JSONP in Spring MVC 3.2

2020-07-10 09:12发布

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.

5条回答
够拽才男人
2楼-- · 2020-07-10 09:19

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

查看更多
\"骚年 ilove
3楼-- · 2020-07-10 09:25

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(); 
   }
查看更多
疯言疯语
4楼-- · 2020-07-10 09:28

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.

查看更多
做个烂人
5楼-- · 2020-07-10 09:35

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.

查看更多
beautiful°
6楼-- · 2020-07-10 09:40

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));
}
查看更多
登录 后发表回答