java跨域请求-JSONP

java  web中如何跨域请求呢?

使用jsonp,详情请参考:http://json-p.org/

页面代码如下:

 

<!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]);//循环输出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> 

 

在浏览器中访问的效果:

 

后台采用spring mvc:

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

JSONPUtil.getJsonP 静态方法的实现如下:

/*** 
     * 用于jsonp调用 
     * @param map : 用于构造json数据 
     * @param callback : 回调的javascript方法名 
     * @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+")";  
    } 

依赖jackson 库

后台返回的内容是:jsonpCallback({"fileName":"a.txt"})

content type是

 

注意:后台返回的形式是:函数名(参数),此处的函数名就是回调函数的名称

 

参考:

spring mvc设置应答体的content type

AJAX 跨域请求 - JSONP获取JSON数据:http://justcoding.iteye.com/blog/1366102

 

App Framework发送JSONP请求(3):

http://hw1287789687.iteye.com/blog/2190719

猜你喜欢

转载自doing19852810.iteye.com/blog/2305125