在有界/无界到 HTTP 会话时获取通知

在有界/无界到 HTTP 会话时获取通知

问题描述:

当我的对象与 HTTP 的会话对象有界/无界时,我如何得到通知.

How can i get notified when my Object gets bounded/unbounded to a session object of HTTP.

让对象的类实现 HttpSessionBindingListener.

Let the object's class implement HttpSessionBindingListener.

public class YourObject implements HttpSessionBindingListener {

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        // The current instance has been bound to the HttpSession.
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        // The current instance has been unbound from the HttpSession.
    }

}

如果您无法控制对象的类代码,因此无法更改其代码,那么另一种方法是实现 HttpSessionAttributeListener.

If you have no control over the object's class code and thus you can't change its code, then an alternative is to implement HttpSessionAttributeListener.

@WebListener
public class YourObjectSessionAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if (event.getValue() instanceof YourObject) {
            // An instance of YourObject has been bound to the session.
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if (event.getValue() instanceof YourObject) {
            // An instance of YourObject has been unbound from the session.
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        if (event.getValue() instanceof YourObject) {
            // An instance of YourObject has been replaced in the session.
        }
    }

}

注意:当您仍然使用 Servlet 2.5 或更早版本时,将 @WebListener 替换为 中的 web.xml 配置条目代码>.

Note: when you're still on Servlet 2.5 or older, replace @WebListener by a <listener> configuration entry in web.xml.