在绑定/无限制到HTTP会话时获取通知

时间:2012-06-29 08:49:23

标签: session servlets notifications

当我的Object被绑定/无限制到HTTP的会话对象时,我如何得到通知。

1 个答案:

答案 0 :(得分:7)

让对象的类实现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

@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中的<listener>配置条目替换web.xml