服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java web支持jsonp的实现代码

java web支持jsonp的实现代码

2021-06-17 11:12燕相识归来 Java教程

这篇文章主要介绍了java web支持jsonp的实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

跨域说明

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

jsonp跨域请求处理

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

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

js代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<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后端处理代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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 暴露的信息

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/chenzd/p/9989682.html

延伸 · 阅读

精彩推荐