3

我用谷歌搜索和stackoverflowed了很多,但不能让它工作。这是我的代码。我在 subscribe 方法中设置了一个会话属性“topic”,但在 sessionDestroyed 中我将其设置为 null。 这个关于 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(). 是因为我使用了不同的会话对象吗?另外,当我打印会话 ID 时。我在所有 3 种方法中都获得了相同的会话 ID。

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

4

2 回答 2

0

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

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

于 2013-09-27T09:25:40.933 回答
-1

在会话创建方法中设置会话属性

@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();
    }

    @Override
    public void sessionCreated(HttpSessionEvent hse) {
        HttpSession session = hse.getSession();
        session.setAttribute("topic", "1");

            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"));
    }
于 2013-09-27T09:13:46.337 回答