SpringBoot專案開發(二十四):支援跨域請求JSONP
阿新 • • 發佈:2018-12-17
在SpringMVC4.1版本以後,Spring為我們提供了一個AbstractJsonpResponseBodyAdvice的類用來支援jsonp的資料,SpringBoot接收解析web請求是依賴於SpringMVC,所以也可以繼承此類
程式碼如下,新增一個配置類,繼承AbstractJsonpResponseBodyAdvice
@ControllerAdvice(basePackages = "com.lkh.tour.controller") public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice { public JsonpAdvice() { super("callback","jsonp"); } }
再寫個測試Controller
@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 ; } }
當傳送請求為:http://localhost:2000/test/testJsonp的時候,結果如下:
當傳送請求為:http://localhost:2000/test/testJsonp?callback=getData,結果如下:
可以看到當我們在請求引數中新增callback引數的時候,返回的資料就是 jsonp 的
當請求引數中不帶callback時,返回的資料是 json 的。可以讓我們方便的靈活運用
再附加一個js的jsonp請求示例
<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>