在我们做项目的过程中,有可能会遇到跨域请求,所以需要我们自己组装支持跨域请求的JSONP数据,而在4.1版本以后的SpringMVC中为我们提供了一个AbstractJsonpResponseBodyAdvice的类用来支持JSONP的数据(SpringBoot接收解析网络请求是依赖于SpringMVC实现的)。下面我们就看一下怎么用AbstractJsonpResponseBodyAdvice来支持跨域请求。
使用AbstractJsonpResponseBodyAdvice来支持跨域请求很简单,只需要继承这个类就可以了。具体代码如下:
包com.zkn.learnspringboot.config; 进口org.springframework.web.bind.annotation.ControllerAdvice; 进口org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;/* * *由wb-zhangkenan> 包com.zkn.learnspringboot.web.controller; 进口com.zkn.learnspringboot.domain.PersonDomain; 进口org.springframework.beans.factory.annotation.Autowired; 进口org.springframework.http.MediaType; 进口org.springframework.web.bind.annotation.RequestMapping; 进口org.springframework.web.bind.annotation.RestController;/* * *由wb-zhangkenan alt="详解SpringBoot多跨域请求的支持(JSONP) ">当我们发送的请求为:http://localhost: 8003/jsonp/testJsonp& # 63;回调=回调的时候,结果如下所示:
看到区别了吗?当我们在请求参数中添加回调参数的时候,返回的数据就是jsonp的,当我们请求参数中不带调的时候,返回的数据是json的。可以让我们方便的灵活运用。下面再奉上一个jsonp的完整案例。
前台页面:
% @ & lt;页面contentType=" text/html; charset=utf - 8”语言=癹ava”%比; & lt; html> & lt; head> & lt; title> Title & lt;脚本src=" https://www.yisu.com/zixun/resources/js/jquery-2.1.4.min.js " type=" text/javascript祝辞& lt;/script> & lt;/head> & lt; body> & lt;输入类型="按钮" value=" https://www.yisu.com/zixun/测试jsonp请求“/比; & lt;脚本type=" text/javascript祝辞 函数testJsonp () { . ajax({美元 类型:“得到”, url: http://localhost: 8003/jsonp/testJsonp, 数据类型:“jsonp”, jsonp:“回调”, 成功:功能(数据){ 警报(数据。用户名+ " " + data.passWord); }, 错误:函数(err) { alert('出现错误了! ! !”); } }); } & lt;/script> & lt;/body> & lt;/html> >之前后台代码1:
包com.zkn.learnspringmvc.news.controller; 进口org.springframework.stereotype.Controller; 进口org.springframework.web.bind.annotation.RequestMapping;/* * *由zkn alt="详解SpringBoot多跨域请求的支持(JSONP) ">当我们点击测试jsopn请求这个按钮的时候,效果如下:
我们成功的实现了一个跨越的请求。更详细的请求信息如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
详解SpringBoot多跨域请求的支持(JSONP)