关于java:JSONP与CORS实现跨域

5次阅读

共计 2553 个字符,预计需要花费 7 分钟才能阅读完成。

JSONP 实现跨域

背景剖析

浏览器出于平安思考,制订了 同源策略。(位于 server1.example.com 的网页无奈与不是 server1.example.com 的服务器沟通)

概述

JSONP(JSON with Padding)是 JSON 的一种“应用模式”,可用于解决支流浏览器的跨域数据拜访的问题

原理

利用 javaScript 中的 src 属性实现近程数据的获取(src 不受同源限度),获取的数据是一个 JS 对象,由浏览器负责解析 JS。
<script type=”text/javascript” src=”http://manage.jt.com/test.json”></script>

实现

页面申请,JS 代码。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSONP 测试 </title>
<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script type="text/javascript">
 $(function(){alert("测试拜访开始!!!!!")
      $.ajax({
         url:"http://manage.jt.com/web/testJSONP",
 type:"get", //jsonp 只能反对 get 申请
 dataType:"jsonp", //dataType 示意返回值类型
 //jsonp: "callback",    // 指定参数名称
 //jsonpCallback: "hello",  // 指定回调函数名称
 success:function (data){   //data 通过 jQuery 封装返回就是 json 串
 alert(data.id);
            alert(data.name);
            alert(data.itemId);
            alert(data.itemDesc);
            // 转化为字符串应用
 //var obj = eval("("+data+")");
 //alert(obj.name); }  
      });    
   })
</script>
</head>
<body>
 <h1>JSON 跨域申请测试 </h1>
</body>
</html>

服务器解决

package com.jt.web.controller;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.ItemDesc;
import com.jt.util.ObjectMapperUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/web/")
public class JSONPController {
    /**
 * 实现 jsonp 跨域拜访
 * url: http://manage.jt.com/web/testJSONP?callback=jQuery111104808002072562081_1610519800035&_=1610519800036
 * 参数:callback=jQuxxxx
 * 返回值:callback(JSON)
 */
 public String jsonp(String callback){ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(101l).setItemDesc("跨域拜访");
        String json = ObjectMapperUtil.toJson(itemDesc);
        return callback+"("+json+")";
    }
    /**
 * * 对于 JSONPObject 的阐明,次要须要本人对 json 类型数据进行转换.
 */ @RequestMapping("testJSONP")
    public JSONPObject jsonp1(String callback){ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(101l).setItemDesc("跨域拜访");
        return new JSONPObject(callback, itemDesc);
    }
}

CORS 形式

跨域资源共享(英语:Cross-origin resource sharing,缩写:CORS),用于让网页的受限资源可能被其余域名的页面拜访的一种机制。(实现跨域),CORS 通过在 响应头 中标识 容许跨域的网址 . 之后同源策略基于安全性的标准予以放行的一种跨域拜访形式.
阐明: 须要在 服务器 中增加容许拜访的标识即可.

package com.jt.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class COUSConfig implements WebMvcConfigurer {
    @Override
 public void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**")// 什么样的申请容许跨域
 .allowedOrigins("http://www.jt.com","*")// 容许通过的门路
 .allowedMethods("*")// 容许什么样的申请形式
 .allowCredentials(true)// 是否容许携带 cookie
 .maxAge(10*60);// 设置跨域通信容许最大时长,默认为 30*60s
 }
}
正文完
 0