Issue
Is there a way to get information about HTTP request from the method down the callstack of the Spring request handler method?
In other words given I have a handler method like:
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
MyInternalClass.doSomeAction();
return String.format("Hello %s!", name);
}
I am looking for means to get the information about HTTP request (such as URL, headers, etc.) within the code of the doSomeAction()
static method in the MyInternalClass
class.
The constraint is that I cannot modify the original method (hello()
).
Solution
You can add a Request parameter of type HttpServletRequest
@GetMapping("/hello")
public String hello(
@RequestParam(value = "name", defaultValue = "World") String name,
HttpServletRequest originalRequest) {
// HERE: call another method here
return String.format("Hello %s!", name);
}
Have a look at the Spring Reference Documentation, Chapter "Method Arguments"
Part 2
However, I was looking for a method that does not force developers to change their code. I will try to add an example to my question, so it will be more verbose.
You can use the RequestContextHolder
to get the request attributes.
HttpServletRequest request =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
.getRequest();
RequestContextHolder.getRequestAttributes()
is a static method, that can be invoked from every where (even for a class that is no Spring Bean). But it is required that it is invoked from a thread that was triggert by a HTTP request.
Answered By - Ralph
Answer Checked By - Senaida (JavaFixing Volunteer)