Spring WebFlux. How to get the request body in two different formats using @RequestBody annotation?(Spring WebFlux。如何使用@RequestBody注释获取两种不同格式的请求正文?)
问题描述
我使用的是Spring Boot 2.5.6和Spring WebFlux。在我的业务案例中,我需要以两种不同的形式使用HTTP请求正文:
- 原始JSON字符串
- 已分析Java DTO
有我的RestContoller
:
@PostMapping("/play")
public Mono<PlayResponse> play(@RequestBody PlayCommand parsedBody,
@RequestBody String jsonBody) {
//code here
}
当我运行测试时,我收到下一个异常:
java.lang.IllegalStateException: Only one connection receive subscriber allowed.
at reactor.netty.channel.FluxReceive.startReceiver(FluxReceive.java:182) ~[reactor-netty-core-1.0.12.jar:1.0.12]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
*__checkpoint ⇢ HTTP POST "/play" [ExceptionHandlingWebHandler]
当我使用下一个方法签名时:
@PostMapping("/play")
public Mono<PlayResponse> play(PlayCommand playCommand,
@RequestBody String body){
//code here
}
PlayCommand parsedBody
将所有字段设置为‘NULL’。
我找不到正确接收身体的方法。
我理解,我可以使用objectMapper
并将playCommand
转换回JSON,但这是不需要完成的额外工作。
可以以两种不同的形式接收请求正文吗?或者,也许我在示例中做错了什么?
推荐答案
不可能有多个@RequestBody
。如果您确实需要原始JSON及其序列化版本,最好的方法是以普通String
的形式接收请求正文,然后将其转换为相应的Java对象,如下所示:
@Autowired
private ObjectMapper objectMapper;
@PostMapping("/play")
public Mono<PlayResponse> play(@RequestBody String body){
PlayCommand playCommand = objectMapper.readValue(body, PlayCommand.class);
}
这篇关于Spring WebFlux。如何使用@RequestBody注释获取两种不同格式的请求正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring WebFlux。如何使用@RequestBody注释获取两种不同格式的请求正文?


基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01