3

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 ?

4
  • 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. Commented Mar 28, 2021 at 7: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. Commented Apr 2, 2021 at 10:39
  • @RaviSoni Did you find what you want? Let me be shared. Thanks. Commented Nov 11, 2021 at 5:55
  • @JinKwon Yes, and have already answered it below. Please vote up if it works. Commented Nov 11, 2021 at 6:05

1 Answer 1

3

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 }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.