springcloud-community / springcloud-comment

0 stars 0 forks source link

post/2022-01/webflux-get-request-anywhere/ #22

Open utterances-bot opened 8 months ago

utterances-bot commented 8 months ago

Get Request object anywhere in Spring WebFlux - Spring Cloud

A different world In a normal Spring Web project, it is very easy to get the Request object and many libraries provide static methods to get it. The code to get it is as follows. 1 2 3 ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); // get the request HttpServletRequest request = requestAttributes.getRequest(); The class RequestContextHolder provides static methods, which means you can call it from anywhere. And it uses ThreadLocal to hold the Request object, which means that different threads can get their own Request objects.

https://www.springcloud.io/post/2022-01/webflux-get-request-anywhere/

dirweis commented 8 months ago

Did I miss something? Where is explained how to use a ServerHttpRequest object in a service bean?

NZhuravlev commented 5 months ago

To get headers in the controller you can just put

@RequestHeader HttpHeaders headers

as an agrument to a controller method, but how do I access it in a service? And how do I add more values to the request context?