tags:

views:

56

answers:

1

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.

+2  A: 

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.requestDestroyed(ServletRequestEvent).attributes</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?

skaffman
Perfect, this did work! I just had the name of the RequestContextListener in the web.xml. What does the requestDestroyed(ServletRequestEvent).attributes do?
wolfcastle
Correct, this is not a Spring MVC app. Sorry, didn't see that the first time I read your answer.
wolfcastle