Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a ServletRequest from inside a singleton spring bean?

Tags:

java

spring

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.

like image 593
wolfcastle Avatar asked Sep 02 '10 20:09

wolfcastle


1 Answers

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?

like image 108
skaffman Avatar answered Nov 10 '22 00:11

skaffman