diff --git a/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensions.kt b/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensions.kt index ddd4e358fe7e..2fd7dcbc61d5 100644 --- a/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensions.kt +++ b/spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensions.kt @@ -35,7 +35,7 @@ import kotlin.reflect.KClass * Extension for [ServerRequest.bodyToMono] providing a `bodyToMono()` variant * leveraging Kotlin reified type parameters. This extension is not subject to type * erasure and retains actual generic type arguments. - * + * * @author Sebastien Deleuze * @since 5.0 */ @@ -192,3 +192,13 @@ fun ServerRequest.Headers.contentLengthOrNull(): Long? = */ fun ServerRequest.Headers.contentTypeOrNull(): MediaType? = contentType().orElse(null) + +/** + * Nullable variant of [ServerRequest.pathVariable]. + * + * @author George Papadopoulos + */ +fun ServerRequest.pathVariableOrNull(name: String): String? { + val vars = pathVariables() + return vars[name] +} \ No newline at end of file diff --git a/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensionsTests.kt b/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensionsTests.kt index 5406a6883c6e..4e8df421a515 100644 --- a/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensionsTests.kt +++ b/spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensionsTests.kt @@ -222,5 +222,19 @@ class ServerRequestExtensionsTests { verify { headers.contentType() } } + @Test + fun `pathVariableOrNull with value`() { + every { request.pathVariables() } returns hashMapOf("name" to "123") + assert(request.pathVariableOrNull("name") == "123") + verify { request.pathVariables() } + } + + @Test + fun `pathVariableOrNull with null`() { + every { request.pathVariables() } returns emptyMap() + assert(request.pathVariableOrNull("name") == null) + verify { request.pathVariables() } + } + class Foo }