【问题标题】:How to get request info on session created in Spring MVC?如何获取在 Spring MVC 中创建的会话的请求信息?
【发布时间】:2015-01-17 04:30:48
【问题描述】:

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

我创建了一个实现 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.

【问题讨论】:

    标签: session spring-mvc ip-address


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,但是 1. 这看起来不像 Bean 定义 2. 我不相信它会被实例化,除非它被其他代码调用。我会从哪里调用它?
    • 如果你正在使用 spring 的组件扫描功能,只需将它放在一个用 @Configuration 注释的类中,然后它就会被拾取。有关 java 配置方式的更多信息,请查看docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/…(尽管其中一些可能已过时)
    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 2011-04-25
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2017-09-17
    相关资源
    最近更新 更多