Session 如何获取SpringMVC中创建的会话的请求信息?

Session 如何获取SpringMVC中创建的会话的请求信息?,session,spring-mvc,ip-address,Session,Spring Mvc,Ip Address,我希望在SpringMVC创建的会话中将一些客户端信息(IP地址等)保存到数据库中 我创建了一个实现HttpSessionListener的类,并在web.xml中对其进行了配置。然而,我不知道接下来该去哪里 也希望能够注入bean(SpringDataJPA存储库) 但是,我已经看到,如果尝试访问RequestContextHolder.currentRequestAttributes(),会出现以下异常: SEVERE: Session event listener threw except

我希望在SpringMVC创建的会话中将一些客户端信息(IP地址等)保存到数据库中

我创建了一个实现HttpSessionListener的类,并在web.xml中对其进行了配置。然而,我不知道接下来该去哪里

也希望能够注入bean(SpringDataJPA存储库)

但是,我已经看到,如果尝试访问RequestContextHolder.currentRequestAttributes(),会出现以下异常:

SEVERE: Session event listener threw exception
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

您可以使用Spring java config以这种方式创建bean:

@Bean
@Named ("IP")
@Scope ("session")
public String ip (HttpServletRequest request) {
  return request.getRemoteAddr ();
}

如果您只想做日志记录,那么您应该使用HttpSessionListener,请提供源代码和完整堆栈跟踪。如有必要,请使用pastebin.com。

Thx,但1。这看起来不像是Bean定义2。我不相信它会被实例化,除非它被其他代码调用。我从哪里调用它呢?如果您使用的是spring的组件扫描功能,只需将它放在一个包中带有@Configuration注释的类中,在这个包中它就会被提取出来。有关更多信息,请查看java配置方式(尽管其中一些可能已经过时)