Spring Boot Webflux: RouterFunctions Add Query Parameters

Viewed 3633

I am trying to figure out how to add query parameters to a route when using RouterFunctions. Here's what I have so far:

  @Bean
public RouterFunction<ServerResponse> routes() {
    return
        RouterFunctions.route()
            .GET("/one/{one}", routeHandlerOne::handlerOne)
            .GET("/two", routeHandlerOne::handlerTwo)
        .build();
}

For route two I want add a query parameter, like /two?three. Any help would be most helpful, thank you!

2 Answers

There is a queryParam() method on the RequestPredicates class you can use.

RouterFunctions.route()
   .GET("/one", RequestPredicates.queryParam("test", t -> true), new CustomHanlder())
   .build();

There are two overloaded methods for queryParam(). One takes the exact value to compare against (javadoc). The second (the one in the example above) takes a predicate and will delegate to the handler function if the predicate returns true (javadoc).

You can then access the query params through the ServerRequest object in your handler function ie.

serverRequest.queryParam("test")

If you want multiple query parameters then you can do it this way

        .GET("/login", RequestPredicates.all()
                .and(queryParam("username", t -> true))
                .and(queryParam("password", t -> true)), handler::login)
Related