I have a singleton spring bean that is being invoked in response to some client side action. I wish to capture some information about the client (specifically the IP address). I assume the best source of this information is the request object. How do I obtain access to the request object from inside my bean?
Forgive me if this is an obvious question, I'm very new to Spring.
I've tried one thing without success.:
((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
.getRequest().getRemoteAddr();
But that failed with an IllegalStateException out of currentRequestAttributes
. The exception text suggests using a RequestContextListener
or RequestContextFilter
I've found a reference to how to configure the RequestContextListener
, but I still don't know to change my bean so I can access the request information.
RequestContextListener
is added to web.xml
, and this will associate the current request with the current thread. This thread association is then retrieved via RequestContextHolder
in the way you've already tried.
So just slap RequestContextListener
into web.xml
, and your code should just start working:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
RequestContextListener
is not normally required in Spring MVC apps, since DispatcherServlet
will do it automatically. I assume this is not a Spring MVC app?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With