spring-framework icon indicating copy to clipboard operation
spring-framework copied to clipboard

Add a non-null variant of `ServerRequest.queryParam()` and `ServerRequest.param()`.

Open earlgrey02 opened this issue 1 year ago • 1 comments

Summary

ServerRequest.paramNotNull()(MVC) and ServerRequest.queryParamNotNull()(WebFlux) has been added to retrieve query parameters that are sure to be non-null without unnecessary null checking (Optional Wrapping, etc.).

Description

In general, functional endpoint allows filtering HTTP requests via RequestPredicates. For query parameters, requests can be mapped only when specific query parameters are received through RequestPredicate.queryParam() or RequestPredicate.param(). If request with a query parameter whose names do not match RequestPredicate is not received, handler mapping is not performed, so request with the corresponding query parameter must exist to reach the handler. In this case, we have determined that null checking for query parameters is unnecessary, so we are posting this PR.

Example

@Configuration
class TestRouter {
    @Bean
    fun testRoutes(handler: TestHandler): RouterFunction<ServerResponse> =
        router {
            // If there is no test query parameter, perform a handler mapping(404 NOT FOUND)
            GET("/test", queryParam("test") { true }, handler::test)
        }
}
@Component
class TestHandler {
    fun test(request: ServerRequest): Mono<ServerResponse> =
        ServerResponse.ok()
            // The test query parameter cannot be null.
            // It is an unnecessary null check(In the case of Java, there is an overhead due to Optional Wrapping)
            .bodyValue(request.queryParamOrNull("test")!!)
}

earlgrey02 avatar May 05 '24 14:05 earlgrey02

Let see with @poutsma when he is available (most of us are on PTO this week) if there is interest for that on Java API side.

sdeleuze avatar May 07 '24 12:05 sdeleuze

Let see with @poutsma when he is available (most of us are on PTO this week) if there is interest for that on Java API side.

I fear that if we add this variant, we would have to do the same for the other SeverRequest methods that return Optional types, thus resulting in four extra methods instead of one. I don't think that adding that much noise in the API is worth it, in Java nor in Kotlin, especially considering that you can accomplish the same via request.servletRequest().getParameter() in Servlet or request.exchange().getRequest().getQueryParams().getFirst() in WebFlux.

poutsma avatar May 15 '24 08:05 poutsma

I tend to agree, and am declining the proposed additional extension.

sdeleuze avatar May 15 '24 08:05 sdeleuze