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?
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.
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); // ... }
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.
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.
Ah! Found it!
It is by doing: req.pathVariable("id")
It was there all the time...in the official Spring Framework (Web Reactive) documentation!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With