文章源自JAVA秀-https://www.javaxiu.com/21250.html 闪耀的瞬间 收藏 分类专栏: 版权 文章源自JAVA秀-https://www.javaxiu.com/21250.html 文章源自JAVA秀-https://www.javaxiu.com/21250.html 在SpringMVC4.1版本以后,Spring为我们提供了一个AbstractJsonpResponseBodyAdvice的类用来支持jsonp的数据,SpringBoot接收解析web请求是依赖于SpringMVC,所以也可以继承此类文章源自JAVA秀-https://www.javaxiu.com/21250.html 代码如下,添加一个配置类,继承AbstractJsonpResponseBodyAdvice文章源自JAVA秀-https://www.javaxiu.com/21250.html 再写个测试Controller文章源自JAVA秀-https://www.javaxiu.com/21250.html 当发送请求为:http://localhost:2000/test/testJsonp的时候,结果如下: 当发送请求为:http://localhost:2000/test/testJsonp?callback=getData,结果如下: 可以看到当我们在请求参数中添加callback参数的时候,返回的数据就是 jsonp 的 当请求参数中不带callback时,返回的数据是 json 的。可以让我们方便的灵活运用文章源自JAVA秀-https://www.javaxiu.com/21250.html 再附加一个js的jsonp请求示例文章源自JAVA秀-https://www.javaxiu.com/21250.html 文章源自JAVA秀-https://www.javaxiu.com/21250.htmlSpringBoot项目开发(二十四):支持跨域请求JSONP
文章源自JAVA秀-https://www.javaxiu.com/21250.html文章源自JAVA秀-https://www.javaxiu.com/21250.html
2018-10-26 15:51:40
496
文章源自JAVA秀-https://www.javaxiu.com/21250.html
1
java
spring boot
SpringBoot 项目开发 文章源自JAVA秀-https://www.javaxiu.com/21250.html@ControllerAdvice(basePackages = "com.lkh.tour.controller")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback","jsonp");
}
}
1234567
@RestController
@RequestMapping("/test")
public class JsonpTestController {
@RequestMapping(value = "/testJsonp",produces = MediaType.APPLICATION_JSON_VALUE)
public Object testJsonp(){
Map<String,String> map = new HashMap<>();
map.put("name","zy");
map.put("age","26");
return map ;
}
}
12345678910111213文章源自JAVA秀-https://www.javaxiu.com/21250.html
文章源自JAVA秀-https://www.javaxiu.com/21250.html
文章源自JAVA秀-https://www.javaxiu.com/21250.html<script type="text/javascript">
function testJsonp() {
$.ajax({
type:'get',
url:'http://localhost:2000/test/testJsonp',
dataType:'jsonp',
jsonp:"callback",
success:function (data) {
alert(data);
},
error:function (err) {
alert('出现错误了!!!');
}
});
}
</script>
12345678910111213141516

评论