I am using Spring annotations, I can pass the HttpRequestContext
from the Controller to the Service.
I am looking for a static way or any better solution than passing RequestContext
around.
I am using Spring annotations, I can pass the HttpRequestContext
from the Controller to the Service.
I am looking for a static way or any better solution than passing RequestContext
around.
If you are using spring you can do the following:
public static HttpServletRequest getCurrentHttpRequest(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
return request;
}
logger.debug("Not called in the context of an HTTP request");
return null;
}
Or the java8 way
public static Optional<HttpServletRequest> getCurrentHttpRequest() {
return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
.filter(ServletRequestAttributes.class::isInstance)
.map(ServletRequestAttributes.class::cast)
.map(ServletRequestAttributes::getRequest);
}
I know, it is already answer. I would like to mark as new update. we can inject HttpServletRequest
by using @Autowired
. It is working fine at springboot
.
@Autowired
private HttpServletRequest httpServletRequest;
For reference, this would be the Kotlin way:
val currentRequest: HttpServletRequest?
get() = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)?.request
In response to @andrebrait comments above "Or the Java 8 way", the methods are present on the ServletRequestAttributes.class
public static Optional<HttpServletRequest> getCurrentHttpRequest() {
return
Optional.ofNullable(
RequestContextHolder.getRequestAttributes()
)
.filter(ServletRequestAttributes.class::isInstance)
.map(ServletRequestAttributes.class::cast)
.map(ServletRequestAttributes::getRequest);
}
You can add HttpServletRequest
as a parameter in controller handler method. Like this:
@GetMapping("/hello")
public String hello(HttpServletRequest request) {
//...
return "Hello world!";
}
List of supported controller method arguments and return types can be found here: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-methods
This is what works for me:
HttpServletRequest request =
((ServletRequestAttributes) Objects.requireNonNull(
RequestContextHolder.getRequestAttributes()))
.getRequest();