How to support JSONP with Spring MVC and multiple response types

I have a method in the controller that will return HTML or JSON depending on what was requested. Here's a stripped down example of such a method, modeled after the information on how to do this, which I found in this question :

@RequestMapping(value="callback")
public ModelAndView callback(@RequestParam("c") String c) {
    Map response = new HashMap<String, String>();
    response.put("foo", "bar");
    return new ModelAndView("fake", "data", new JSONPObject(c, response));
}

I put a JSONPObject in the model because I need to be able to get it from a view that displays if HTML was requested. But this poses a problem when I handle JSON with a callback:

curl 'http://localhost:8080/notes/callback.json?c=call'
{"data"call(:{"foo":"bar"})}

As you can see, since I put my data in the β€œdata” slot in the model, when the model is displayed as JSON, there is additional packaging. What I'm looking for is a JSON rendering (technically JSONP), which looks like this:

call({"data":{"foo":"bar"}})

- , , , JSONPObject ?

+3
2

. JSON Spring MappingJacksonJsonView . , , . .

    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" >
                <property name="extractValueFromSingleKeyModel" value="true" />
            </bean>
        </list>
    </property>
0

JSONP Spring MVC, :

:

@RequestMapping(value="/notes/callback.json", method=RequestMethod.GET)
public void jsonpCallback(@RequestParam("callback") String callback, HttpServletResponse response) {
   response.setContentType("text/javascript; charset=UTF-8");
   PrintWriter out = response.getWriter();
   out.print(callback + "(" + jsonDataString + ")");
}

:

<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">

function yourfunction() {
    jQuery.getJSON("http://localhost:8080/notes/callback.json?callback=?", 
        function(data) {
            alert(data.someParam);
        });
}

</script>
+7

All Articles