Here’s a code snippet demonstrating how to wrap JSON text within a JSONP response.
The text of the JSON object is in the string json. The variable resp represents a HttpServletResponseobject. Callback represents contents of the HTTP parameter callback , which should be set with the name of the Javascript function to call. Before calling this code, it’s a good idea to validate that parameter.
String callback = req.getParameter("callback");
String json_text = callback + "(" + json + ");";
resp.getWriter().println(json_text);
Here’s an example of a simple JSONP response:
findIP({"ip": "8.8.8.8"});
This response will call the JS function findIP (the callback parameter contents), with an object containing the property ip (the JSON data).