1:在Spring Boot的Api服务器上进行配置
package me.loveshare.note1.configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
/**
* Created by Tony on 2017/8/1.
* Spring Boot支持跨域请求的JSONP数据.
*/
@ControllerAdvice(basePackages = {"me.loveshare.note1.api"})
public class JSONPConfiguration extends AbstractJsonpResponseBodyAdvice {
public JSONPConfiguration() {
super("callback", "jsonp");
}
}
2:Jsonp测试
2.1:测试api接口配置
package me.loveshare.note1.api;
import lombok.extern.slf4j.Slf4j;
import me.loveshare.note1.data.entity.bo.common.JsonResult;
import me.loveshare.note1.data.entity.bo.common.JsonResultMethod;
import me.loveshare.note1.data.utils.DateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* Created by Tony on 2017/8/4.
*/
@Slf4j
@RestController
public class TestDataApi extends BaseApi {
/**
* json数据测试
*/
@RequestMapping(value = "test", produces = "application/json; charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST})
public JsonResult initDbDatasC() {
return JsonResultMethod.code_200("The request completed successfully.", DateUtils.timestamp(new Date()));
}
}
2.2:json请求测试: http://192.168.1.119:5201/note1/test.json
{"code":200,"message":"The request completed successfully.","data":"2017-08-11 17:55:33:248"}
2.3:jsonp请求测试: http://192.168.1.119:5201/note1/test.json?callback=myFunc
/**/myFunc({"code":200,"message":"The request completed successfully.","data":"2017-08-11 17:55:52:774"});
3:前段web的部分js的ajax请求代码:
function jsonpTestFunc() {
var req_data = {"pageIndex": 1, "pageSize": 5};
if (lock_req) return false;
lock_req = true;
$.ajax({
url: "http://192.168.1.119:5201/note1/userinfo/list.json?time=" + Date.parse(new Date()),
type: "POST",
data: req_data,
dataType: "jsonp", //返回JSONP格式的数据,此值固定
jsonp: "callback", //回调函数的名字,此值固定
timeout: 30000,
success: function (data) {
console.log(JSON.stringify(data));
lock_req = false;
},
error: function () {
lock_req = false;
}
});
}
服务器请求日志:
User-Access-Args:{"protocol":"HTTP/1.1(http)","ip":"192.168.2.152","port":"49985","method":"GET","url":"/note1/userinfo/list.json?time=1502508020000&callback=jQuery32105595664549758419_1502508020161&pageIndex=1&pageSize=5&_=1502508020162","user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36","uAT":"null"}
注:jsonp请求本质是GET请求,故安全数据请慎用!
更多请参考:
json的研究: http://blog.csdn.net/typa01_kk/article/details/50970274
GitHub的API源代码: https://github.com/typa01/spring-boot/tree/master/spring-boot-note1
GitHub的WEB-JS源代码: https://github.com/typa01/web/blob/master/html/page.html