2012-06-29 27 views

Trả lời

7

Để lớp của đối tượng triển khai 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. 
    } 

} 

Nếu bạn không có quyền kiểm soát mã lớp của đối tượng và do đó bạn không thể thay đổi mã của nó, sau đó một sự thay thế là thực hiện 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. 
     } 
    } 

} 

Lưu ý: khi bạn vẫn còn trên Servlet 2.5 trở lên, thay thế @WebListener bởi một mục <listener> cấu hình trong web.xml.

+0

cảm ơn sự trợ giúp. Đây là những gì tôi đang tìm kiếm :) – ramoh

Các vấn đề liên quan