當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【springboot】【若依(ruoyi)】@RestController 接口支持 JSONP
生活随笔
收集整理的這篇文章主要介紹了
【springboot】【若依(ruoyi)】@RestController 接口支持 JSONP
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
- 若依(ruoyi): v4.3
- springboot 2.1.1.RELEASE
- spring 5.1.3.RELEASE
- 360極速瀏覽器 12.0.1476.0 (正式版本) (32 位)
- jquery 3.5.0
簡單來說,@RestController 接口支持 JSONP 需要對返回結(jié)果用callback包裹。
需求為:
- jsonpCallback 固定為 callback。
- JSONP 開關(guān)參數(shù)為 jsonp。比如:http://localhost:8085/api/sample/form/get1?jsonp=1輸出 callback({"code":0,"msg":"OK"});,http://localhost:8085/api/sample/form/get1 輸出 {"code":0,"msg":"OK"}
操作步驟
- 編寫 MappingJackson2HttpMessageConverterSupportJsonp類,且繼承 MappingJackson2HttpMessageConverter 類。
- 在 MappingJackson2HttpMessageConverterSupportJsonp類中覆蓋 writePrefix(在輸出時(shí),添加前綴) 和 writeSuffix(在輸出時(shí),添加后綴)。
- 使用 MappingJackson2HttpMessageConverterSupportJsonp Bean 替換 MappingJackson2HttpMessageConverter Bean。
代碼如下:
@Configuration public class JsonpSupportConfig {@Beanpublic MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {return new MappingJackson2HttpMessageConverterSupportJsonp(objectMapper);}private static class MappingJackson2HttpMessageConverterSupportJsonp extends MappingJackson2HttpMessageConverter {private final String PARAM_JSONP = "jsonp";public MappingJackson2HttpMessageConverterSupportJsonp(ObjectMapper objectMapper) {super(objectMapper);}@Overrideprotected void writePrefix(JsonGenerator generator, Object object) throws IOException {if (this.isJsonp(object)) {generator.writeRaw("callback(");}}@Overrideprotected void writeSuffix(JsonGenerator generator, Object object) throws IOException {if (this.isJsonp(object)) {generator.writeRaw(")");}}private boolean isJsonp(Object object) {RequestAttributes attributes = RequestContextHolder.getRequestAttributes();ServletRequestAttributes servletAttributes = (ServletRequestAttributes) attributes;HttpServletRequest request = servletAttributes.getRequest();String jsonpStr = request.getParameter(PARAM_JSONP);if ("0".equals(jsonpStr)) { return false; }if ("1".equals(jsonpStr)) { return true; }return Boolean.valueOf(jsonpStr);}} }效果圖:
spring boot 對 jsonp 的支持問題
spring 5.1 之前可以使用 AbstractJsonpResponseBodyAdvice 支持JSONP,spring 5.1之后將其移除了。
AbstractJsonpResponseBodyAdvice was deprecated starting from Spring 5.0.7 and 4.3.18 and in version 5.1 it is completely removed.
因?yàn)殡S著時(shí)間的推移,瀏覽器都支持了 CROS 。CROS 要比 JSONP 好。工作中,逐漸的轉(zhuǎn)投 CROS。
參考
https://blog.csdn.net/sayyy/article/details/108399070
https://stackoverflow.com/questions/52845927/how-to-handle-jsonp-spring-framework-5-1
總結(jié)
以上是生活随笔為你收集整理的【springboot】【若依(ruoyi)】@RestController 接口支持 JSONP的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多名房客被智能音箱偷拍,小度回应:仅管理
- 下一篇: 浅论系统重装的几种方法没有光盘如何重装电