简体   繁体   English

如何从单例spring bean中访问ServletRequest?

[英]How to access a ServletRequest from inside a singleton spring bean?

I have a singleton spring bean that is being invoked in response to some client side action. 我有一个单独的spring bean,它被调用以响应一些客户端操作。 I wish to capture some information about the client (specifically the IP address). 我想捕获一些有关客户端的信息(特别是IP地址)。 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? 如何从bean内部获取对请求对象的访问权限?

Forgive me if this is an obvious question, I'm very new to Spring. 如果这是一个显而易见的问题,请原谅我,我对Spring很新。

I've tried one thing without success.: 我尝试了一件没有成功的事:

((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
.getRequest().getRemoteAddr();

But that failed with an IllegalStateException out of currentRequestAttributes . 但是在currentRequestAttributes出现IllegalStateException失败了。 The exception text suggests using a RequestContextListener or RequestContextFilter 异常文本建议使用RequestContextListenerRequestContextFilter

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参考 ,但我仍然不知道要更改我的bean,以便我可以访问请求信息。

RequestContextListener is added to web.xml , and this will associate the current request with the current thread. RequestContextListener被添加到web.xml ,这将当前请求与当前线程相关联。 This thread association is then retrieved via RequestContextHolder in the way you've already tried. 然后以您已经尝试过的方式通过RequestContextHolder检索此线程关联。

So just slap RequestContextListener into web.xml , and your code should just start working: 所以只需将RequestContextListener web.xml ,你的代码就应该开始工作了:

<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. Spring MVC应用程序通常不需要RequestContextListener ,因为DispatcherServlet会自动执行。 I assume this is not a Spring MVC app? 我假设这不是一个Spring MVC应用程序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM