@RequestBody
您可以使用 @RequestBody
注解,通过 HttpMessageReader 将请求主体读取并反序列化为 Object
。以下示例使用 @RequestBody
参数:
You can use the @RequestBody
annotation to have the request body read and deserialized into an
Object
through an HttpMessageReader.
The following example uses a @RequestBody
argument:
-
Java
-
Kotlin
@PostMapping("/accounts")
public void handle(@RequestBody Account account) {
// ...
}
@PostMapping("/accounts")
fun handle(@RequestBody account: Account) {
// ...
}
与 Spring MVC 不同的是,在 WebFlux 中,@RequestBody
方法参数支持响应式类型,并且完全支持非阻塞读取和(客户端到服务器)流处理。
Unlike Spring MVC, in WebFlux, the @RequestBody
method argument supports reactive types
and fully non-blocking reading and (client-to-server) streaming.
-
Java
-
Kotlin
@PostMapping("/accounts")
public void handle(@RequestBody Mono<Account> account) {
// ...
}
@PostMapping("/accounts")
fun handle(@RequestBody accounts: Flow<Account>) {
// ...
}
您可以使用 WebFlux Config 的 HTTP message codecs 选项来配置或自定义消息读取器。
You can use the HTTP message codecs option of the WebFlux Config to configure or customize message readers.
可以结合使用 @RequestBody
和 jakarta.validation.Valid
或 Spring 的 @Validated
注解,这会导致应用标准 Bean 验证。验证错误会导致 WebExchangeBindException
,进而导致 400 (BAD_REQUEST) 响应。该异常包含错误详细信息的 BindingResult
,并且可以在控制器方法中通过使用异步包装器声明参数,然后使用错误相关运算符来处理它:
You can use @RequestBody
in combination with jakarta.validation.Valid
or Spring’s
@Validated
annotation, which causes Standard Bean Validation to be applied. Validation
errors cause a WebExchangeBindException
, which results in a 400 (BAD_REQUEST) response.
The exception contains a BindingResult
with error details and can be handled in the
controller method by declaring the argument with an async wrapper and then using error
related operators:
-
Java
-
Kotlin
@PostMapping("/accounts")
public void handle(@Valid @RequestBody Mono<Account> account) {
// use one of the onError* operators...
}
@PostMapping("/accounts")
fun handle(@Valid @RequestBody account: Mono<Account>) {
// ...
}
还可以声明一个 Errors
参数来访问验证错误,但在这种情况下,请求正文不能是 Mono
,并且必须首先解决:
You can also declare an Errors
parameter for access to validation errors, but in
that case the request body must not be a Mono
, and will be resolved first:
-
Java
-
Kotlin
@PostMapping("/accounts")
public void handle(@Valid @RequestBody Account account, Errors errors) {
// use one of the onError* operators...
}
@PostMapping("/accounts")
fun handle(@Valid @RequestBody account: Mono<Account>) {
// ...
}
如果方法验证适用,因为其他参数有 @Constraint
注解,那么就引发 HandlerMethodValidationException
。有关更多详细信息,请参阅 Validation 部分。
If method validation applies because other parameters have @Constraint
annotations,
then HandlerMethodValidationException
is raised instead. For more details, see the
section on Validation.