Implementing JSONP in Spring MVC 3.2

走远了吗. 提交于 2019-12-21 12:56:00

问题


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.


回答1:


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));
}



回答2:


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




回答3:


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.




回答4:


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.




回答5:


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(); 
   }


来源:https://stackoverflow.com/questions/15282617/implementing-jsonp-in-spring-mvc-3-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!