如何获取在 Spring MVC 中创建的会话的请求信息?
How to get request info on session created in Spring MVC?
我希望将一些客户端信息(IP 地址等)保存到 Spring MVC 中创建的会话的数据库中。
我创建了一个 class 实现 HttpSessionListener 并在 web.xml 中配置了它。但是,我不确定之后该去哪里。
也希望能够注入一个 bean(Spring Data JPA 存储库)。
我见过 How to get the IP address when a session is created? ,但是如果我尝试访问 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 配置这样创建一个 bean:
@Bean
@Named ("IP")
@Scope ("session")
public String ip (HttpServletRequest request) {
return request.getRemoteAddr ();
}
如果您只想记录日志,那么您应该使用 HttpSessionListener,请提供您的源代码和完整的堆栈跟踪。如有必要,请使用 pastebin.com。
我希望将一些客户端信息(IP 地址等)保存到 Spring MVC 中创建的会话的数据库中。
我创建了一个 class 实现 HttpSessionListener 并在 web.xml 中配置了它。但是,我不确定之后该去哪里。
也希望能够注入一个 bean(Spring Data JPA 存储库)。
我见过 How to get the IP address when a session is created? ,但是如果我尝试访问 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 配置这样创建一个 bean:
@Bean
@Named ("IP")
@Scope ("session")
public String ip (HttpServletRequest request) {
return request.getRemoteAddr ();
}
如果您只想记录日志,那么您应该使用 HttpSessionListener,请提供您的源代码和完整的堆栈跟踪。如有必要,请使用 pastebin.com。