Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve path variable on Spring Boot WebFlux (functional approach)

Let's say I have this router definition:

@Component
class PersonRouter(private val handler: PersonHandler) {
  @Bean
  fun router(): RouterFunction<ServerResponse> = router {
    ("/api/people" and accept(MediaType.APPLICATION_JSON_UTF8)).nest {
      GET("/{id}") { handler.findById(it) }
    }
  }

And then this handler:

@Component
@Transactional
class PersonHandler(private val repository: PersonRepository) {
  private companion object : KLogging()

  @Transactional(readOnly = true)
  fun findById(req: ServerRequest): Mono<ServerResponse> {
    logger.info { "${req.method()} ${req.path()}" }
    val uuid = ? // req.pathContainer().elements().last().value()
    return ServerResponse.ok()
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(BodyInserters.fromObject(repository.findById(uuid)))
        .switchIfEmpty(ServerResponse.notFound().build())
  }
}

How do I access the identifier (what would be a @PathVariable id: String on a typical @RestController) from ServerRequest without doing black magic with regular expressions, string-heavy-lifting, and such things?

like image 715
x80486 Avatar asked Jul 30 '18 02:07

x80486


People also ask

Is PATH variable spring boot optional?

Making Path Variables OptionalSince the required attribute is false, Spring will not complain if the id path variable is not sent in the request. That is, Spring will set articleId to id if it's sent, or null otherwise. On the other hand, if required was true, Spring would throw an exception in case id was missing.

What is Routerfunctions?

RouterFunction serves as an alternative to the @RequestMapping annotation. We can use it to route requests to the handler functions: @FunctionalInterface public interface RouterFunction<T extends ServerResponse> { Mono<HandlerFunction<T>> route(ServerRequest request); // ... }

Is PATH variable mandatory?

3 version, @PathVariable annotation has required attribute, to specify it is mandatorily required in URI. The default value for this attribute is true if we make this attribute value to false, then Spring MVC will not throw an exception.

What is a functional endpoint?

fn, a lightweight functional programming model in which functions are used to route and handle requests and contracts are designed for immutability. It is an alternative to the annotation-based programming model but otherwise runs on the same webflux-reactive-spring-web foundation.


1 Answers

Ah! Found it!

It is by doing: req.pathVariable("id")

It was there all the time...in the official Spring Framework (Web Reactive) documentation!

like image 126
x80486 Avatar answered Sep 20 '22 03:09

x80486