当前位置: 移动技术网 > IT编程>开发语言>Java > java web支持jsonp的实现代码

java web支持jsonp的实现代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

跨域说明

跨域指请求和服务的域不一致,浏览器和h5的ajax请求有影响,而对服务端之间的http请求没有限制。
跨域是浏览器拦截了服务器端返回的相应,不是拦截了请求。

jsonp跨域请求处理

jsonp(json with padding) 是 json的一种"使用模式",可以让网页从别的域名(网站)那获取资料,绕过同源策略(若地址里面的协议、域名和端口号均相同则属于同源),即跨域读取数据。

jsonp:利用script标签可以跨域,让服务器端返回可执行的javascript函数,参数为要回发的数据。可看做带有回调函数的ajax请求。

js代码

<script type="text/javascript"> 
$(function(){   
  /* 
  //简写形式,效果相同 
  $.getjson("http://app.example.com/base/json.do?sid=1494&busiid=101&jsonpcallback=?", 
      function(data){ 
        $("#showcontent").text("result:"+data.result) 
  }); 
  */ 
  $.ajax({ 
    type : "get", 
    async:false, 
    url : "http:/xxx", 
    datatype : "jsonp",//数据类型为jsonp 
    jsonp: "jsonpcallback",//服务端用于接收callback调用的function名的参数 
    jsonpcallback:"自定义回调函数名"
    success : function(data){ 
      alert(data.info) 
    }, 
    error:function(){ 
      alert('fail'); 
    } 
  });  
}); 
</script>

java后端处理代码

@responsebody
  @requestmapping(value = "/url", produces= mediatype.application_json)
  public string test(
            httpservletrequest request,
            httpservletresponse response) throws exception{
    string result = getresult();
    response.setheader("pragma", "no-cache");
    response.setheader("cache-control", "private,no-cache,no-store,max-age=0");
    response.setdateheader("expires", 0);
    string str=request.getparameter("jsonpcallback");
    if (str==null||str.equals("")) {
      return result;
    } else {
      return str + "(" + result + ")";
    }
  }

cors(协议跨域资源共享)(cross-origin resource sharing)

它允许浏览器向跨源服务器,发出xmlhttprequest请求,从而克服了ajax只能同源使用的限制 详细介绍

  • access-control-allow-origin:* 允许所有域名的脚本访问该资源
  • access-control-allow-methods:get,post,put,delete,options 运行什么方式访问资源
  • access-control-expose-headers:x-requested-with 暴露的信息

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网