Skip to content

Commit 15f8863

Browse files
committed
Add sub-section on validation for functional endpoints
Issue: SPR-17401
1 parent bc3b95d commit 15f8863

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/docs/asciidoc/web/webflux-functional.adoc

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,47 @@ found. If it is not found, we use `switchIfEmpty(Mono<T>)` to return a 404 Not F
252252

253253

254254

255+
[[webflux-fn-handler-validation]]
256+
=== Validation
257+
258+
A functional endpoint can use Spring's <<core.adoc#validation,validation facilities>> to
259+
apply validation to the request body. For example, given a custom Spring
260+
<<core.adoc#validation,Validator>> implementation for a `Person`:
261+
262+
====
263+
[source,java,indent=0]
264+
[subs="verbatim,quotes"]
265+
----
266+
public class PersonHandler {
267+
268+
private final Validator validator = new PersonValidator(); // <1>
269+
270+
// ...
271+
272+
public Mono<ServerResponse> createPerson(ServerRequest request) {
273+
Mono<Person> person = request.bodyToMono(Person.class).doOnNext(this::validate); <2>
274+
return ok().build(repository.savePerson(person));
275+
}
276+
277+
private void validate(Person person) {
278+
Errors errors = new BeanPropertyBindingResult(body, "person");
279+
validator.validate(body, errors);
280+
if (errors.hasErrors) {
281+
throw new ServerWebInputException(errors.toString()); <3>
282+
}
283+
}
284+
285+
----
286+
<1> Create `Validator` instance.
287+
<2> Apply validation.
288+
<3> Raise exception for a 400 response.
289+
====
290+
291+
Handlers can also use the standard bean validation API (JSR-303) by creating and injecting
292+
a global `Validator` instance based on `LocalValidatorFactoryBean`.
293+
See <<core.adoc#validation-beanvalidation,Spring Validation>>.
294+
295+
255296

256297
[[webflux-fn-router-functions]]
257298
== `RouterFunction`

0 commit comments

Comments
 (0)