Similar to Is there a static way to get the current HttpServletRequest in Spring, I want to get ServerHttpRequest in my spring webflux project via a static method, so i don't need to pass it across multiple layers all the way from controller. What's the best way to achieve this ?
Asked
Active
Viewed 2,591 times
2
-
`ServerWebExchange` should be available in the subscriber context. `static` access relies on threadlocals - which for obvious reasons don’t work with reactive; at least not without significant problems. – Boris the Spider Mar 28 '21 at 07:47
-
Subscriber Context has been deprecated, and usage of deferContextual is recommended as per spring java docs, which can be used in static way as well. One solution has been mentioned below. – Ravi Soni Apr 02 '21 at 10:39
-
@RaviSoni Did you find what you want? Let me be shared. Thanks. – Jin Kwon Nov 11 '21 at 05:55
-
@JinKwon Yes, and have already answered it below. Please vote up if it works. – Ravi Soni Nov 11 '21 at 06:05
1 Answers
2
Below is the static way to get the context for the current request:
Note: If getServerHttpRequest() is blocked, then only the keys which have been set by that point will be available.
public static Mono<ServerHttpRequest> getServerHttpRequest() {
return Mono.deferContextual(Mono::just)
.map(contextView -> contextView.get(ServerWebExchange.class).getRequest());
}
Also, it could be achieved via :
mono.subscriberContext // deprecated
And recently, Springflux has introduced "transformDeferredContextual" which is a more cleaner approach:
mono.transformDeferredContextual( (orginialMono, context ) -> {
... do something
return orginialMono; // later this will be flatmapped
});

Ravi Soni
- 953
- 1
- 7
- 17