简单来说,@RestController 接口支持 JSONP 需要对返回结果用callback包裹。
需求为:
jsonpCallback 固定为 callback。JSONP 开关参数为 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"}代码如下:
@Configuration public class JsonpSupportConfig { @Bean public 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); } @Override protected void writePrefix(JsonGenerator generator, Object object) throws IOException { if (this.isJsonp(object)) { generator.writeRaw("callback("); } } @Override protected 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 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.
因为随着时间的推移,浏览器都支持了 CROS 。CROS 要比 JSONP 好。工作中,逐渐的转投 CROS。
https://blog.csdn.net/sayyy/article/details/108399070 https://stackoverflow.com/questions/52845927/how-to-handle-jsonp-spring-framework-5-1
