HandlerFunction

HandlerFunction accepts a ServerRequest object and returns Mono<ServerResponse>. Both ServerRequest and ServerResponse objects are immutable and fully reactive, built on top of Reactor.

ServerRequest exposes the body as Mono or Flux. Traditionally, BodyExtractor is used to achieve this. However, it also has utility methods which exposes these objects as shown in the following code. ServerRequest also gives access to all HTTP request elements, such as method, URI, and query string parameters:

Mono<String> helloWorld = request.body(BodyExtractors.toMono(String.class);
Mono<String> helloWorldUtil = request.bodyToMono(String.class);

Flux<Person> movie = request.body(BodyExtractors.toFlux(Movie.class);
Flux<Person> movieUtil = request.bodyToFlux(Movie.class);

The ServerResponse object gives you access to various HTTP responses. The ServerResponse object can be created by using a builder, which allows setting response status and response headers. It also allows you to set the response body:

Mono<Movie> movie = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(movie);

HandlerFunction can be created using a Lambda function as in the following code and return ServerResponse with status 200 OK and with a body based on a String:

HandlerFunction<ServerResponse> handlerFunction =
request -> ServerResponse.ok().body(fromObject("Sample HandlerFunction"));

It is recommended to group all HandlerFunction objects into a single class having multiple methods, each handling a specific function, as shown in the following code snippet:

public class MovieHandler {
public Mono<ServerResponse> listMovies(ServerRequest request) {
// Logic that returns all Movies objects
}
public Mono<ServerResponse> createMovie(ServerRequest request) {
// Logic that returns creates Movie object in the request object
}
public Mono<ServerResponse> getMovie(ServerRequest request) {
// Logic that returns one Movie object
}
//.. More methods as needed
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.106.191