【发布时间】:2021-03-05 16:38:17
【问题描述】:
从 Spring 4 迁移到 Spring 5.1 时,我很难处理 JSONP
Spring 4 为 jsonp 提供 AbstractJsonpResponseBodyAdvice 类
但是,AbstractJsonpResponseBodyAdvice 类在 Spring 5 中消失了。
Spring 5.1 有补课吗???
【问题讨论】:
标签: spring
从 Spring 4 迁移到 Spring 5.1 时,我很难处理 JSONP
Spring 4 为 jsonp 提供 AbstractJsonpResponseBodyAdvice 类
但是,AbstractJsonpResponseBodyAdvice 类在 Spring 5 中消失了。
Spring 5.1 有补课吗???
【问题讨论】:
标签: spring
AbstractJsonpResponseBodyAdvice 从 Spring 5.0.7 和 4.3.18 开始被弃用,在 5.1 版本中它被完全删除。 Spring 5.1 中没有直接替代品,而不是使用不安全的 JSON-P,您应该迁移到 CORS(跨域资源共享),它允许您指定授权哪种跨域请求。
在此处阅读 Spring 文档中有关 CORS 的更多信息:https://docs.spring.io/spring/docs/5.0.x/spring-framework-reference/web.html#mvc-cors
关于 SO 上的 CORS 也有很多问题 - 例如:How to configure CORS in a Spring Boot + Spring Security application?
当然,总是有一个肮脏的选择,您可以将AbstractJsonpResponseBodyAdvice 类及其所有依赖项拆开到单独的 jar 中,并在新版本的 Spring 中使用它,但我认为最好从 CORS 开始;-)
【讨论】:
我用原始代码处理它:
// http://127.0.0.1:8080/jsonp/test?callback=json_123456
@GetMapping(value = "/test")
public void testJsonp(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
@RequestParam(value = "callback", required = false) String callback) throws IOException {
JSONObject json = new JSONObject();
json.put("a", 1);
json.put("b", "test");
String dataString = json.toJSONString();
if (StringUtils.isBlank(callback)) {
httpServletResponse.setContentType("application/json; charset=UTF-8");
httpServletResponse.getWriter().print(dataString);
} else {
// important: contentType must be text/javascript
httpServletResponse.setContentType("text/javascript; charset=UTF-8");
dataString = callback + "(" + dataString + ")";
httpServletResponse.getWriter().print(dataString);
}
// return dataString;
}
【讨论】: