java - 没有在 HttpSessionListener 的 sessionDestroyed() 方法中获取 session 属性

标签 java session httpsession

我用 google 和 stackoverflow 搜索了很多,但无法让它工作。这是我的代码。 我在 subscribe 方法中设置了一个 session 属性“topic”,但在 sessionDestroyed 中我将其设置为 null。 This question在 SO 上似乎与我相关,但没有解决问题。

@Path("/jpubsub/{topic}")
    public class JMSSubscribe implements HttpSessionListener, ServletContextListener, MessageListener, ExceptionListener {
    
        @GET
        public subscribe(@javax.ws.rs.core.Context HttpServletRequest request) {
            HttpSession session = request.getSession();
            session.setAttribute("topic", "1");
        }
    
        @Override
        public void sessionCreated(HttpSessionEvent hse) {
            HttpSession session = hse.getSession();
                System.out.println("Created Session - ID : " + session.getId());
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent hse) {
                System.out.println("Destroyed Session - ID : " + hse.getSession().getId());
                System.out.println("Topic ID sessionDestroyed - " + hse.getSession().getAttribute("topic"));
        }

请帮忙。

PS:当我在 sessionCreated() 中设置属性时,我在 sessionDestroyed() 中获取它。 是因为我使用不同的 session 对象吗?另外,当我打印 session ID 时。我在所有 3 种方法中都获得了相同的 session ID。

请询问是否需要任何其他代码。

最佳答案

调用sessionDestroyed() 后, session 中的所有对象都已被清除。因此,你得到空值。相反,您应该实现 HttpSessionBindingListener界面。

并且不要使用原始字符串对象存储在 session 中,而是创建一个实现上述接口(interface)的简单对象。当它从 session 中解除绑定(bind)(删除)时,您将获得该值。假设没有其他人删除它,它只会在 session 实际销毁之前被调用。

关于java - 没有在 HttpSessionListener 的 sessionDestroyed() 方法中获取 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19046976/

相关文章:

java - 设置为新的 DefaultListModel 时 JList 不更新

Android:登录网站并使用 DefaultHttpClient 保留 session /cookie

php - 如何在 Laravel 中设置 session 超时?

java - 在 GAE 中使用 HttpSession 时,我还需要做什么?

java - HttpSession 作为 Controller 中的参数

java - Spring-boot - 参数化测试 - 访问MethodSource中的Application.properties

java - 带有 Java 11 : Unable to resolve persistence unit root URL 的 Spring Boot 2.1

java - 我可以使用 session 作用域 bean 而不是 httpsession 来维护 session 吗

java - 将参数链接到函数

php - 使用 mysql 和 php 将用户名从 session 记录到表中