http://hw1287789687.iteye.com/blog/2188617
How do I cross-domain requests in the Java Web?
For more information, please refer to Jsonp: http://json-p.org/
The page code is as follows:
HTML code
- <! DOCTYPE HTML>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title></title>
- <script type="Application/javascript" >
- function Jsonpcallback (Result) {
- Alert (json.stringify (result));
- /*for (var i in result) {
- Alert (i+ ":" +result[i]);//loop output a:1,b:2,etc.
- } */
- }
- var jsonp=document.createelement ("script");
- jsonp.type="Text/javascript";
- jsonp.src="Http://192.168.0.100:8080/tv_mobile/video/text2?callback=jsonpCallback";
- document.getElementsByTagName ("Head") [0].appendchild (JSONP);
- </Script>
- </head>
- <body>
- </body>
- </html>
Effects that are accessed in the browser:
The background uses spring MVC:
Java code
- @ResponseBody
- @RequestMapping (value = "/text2", Produces=systemhwutil.response_contenttype_javascript2)
- Public String Text2 (httpservletrequest request, HttpServletResponse response,string Contenttype2,string callback)
- throws IOException {
- String content = null;
- Map map = new HashMap ();
- Map.put ("FileName", "a.txt");
- CONTENT=JSONPUTIL.GETJSONP (map, callback);
- SYSTEM.OUT.PRINTLN (content);
- return content;
- }
The Jsonputil.getjsonp static method is implemented as follows:
Java code
- /***
- * For JSONP calls
- * @param map: Used to construct JSON data
- * @param callback: The JavaScript method name of the callback
- * @return
- */
- public static String Getjsonp (Map map,string callback)
- {
- Objectmapper mapper = new Objectmapper ();
- String content = null;
- try {
- Content = mapper.writevalueasstring (map);
- SYSTEM.OUT.PRINTLN (content);
- } catch (Jsongenerationexception e) {
- E.printstacktrace ();
- } catch (Jsonmappingexception e) {
- E.printstacktrace ();
- } catch (IOException e) {
- E.printstacktrace ();
- }
- if (Valuewidget.isnullorempty (callback)) {
- return content;
- }
- return callback+"(" +content+")";
- }
Rely on the Jackson Library
What is returned in the background is:jsonpcallback ({"FileName": "A.txt"})
Content Type is
Note: The form returned in the background is the function name ( parameter), where the function name is the name of the callback function
Reference:
Spring MVC sets the content type of the responder body
AJAX cross-domain request-JSONP get JSON data:http://justcoding.iteye.com/blog/1366102
APP Framework Send JSONP request (3): http://hw1287789687.iteye.com/blog/2190719
Java Web get request cross-domain (GO)