Invoke method just before session expires

后端 未结 2 1631
北海茫月
北海茫月 2020-11-29 08:43

My webapp has users who login. There is a timeout. Before the session expires, I would like to execute a method to cleanup some locks.

I\'ve implemented a sess

相关标签:
2条回答
  • 2020-11-29 09:01

    One more elegant solution:

    Just add a @PreDestroy Annotation to a Session-Bean! If the Session is going to be destroyed, it will call PreDestroy on all SessionBeans beforehand, there you can logout and everything!

    Although this doesn't currently work with many ApplicationServers, seems to be an unclear segment of the JSF Specification. So going with the accepted answer (HttpSessionBindingListener) will be necessary, until @PreDestroy will work as intended on all servers.

    0 讨论(0)
  • 2020-11-29 09:02

    You can achieve that by implementing a HttpSessionBindingListener you need to register a session which holds a lock by calling registerSession (the string "sessionBindingListener" may not be changed). The container will callback the valueUnbound() method after the session timed out and before the session is destroyed.

    public class ObjectLock implements Serializable,HttpSessionBindingListener {
        public void valueBound(HttpSessionBindingEvent event) {
            log.info("valueBound:" + event.getName() + " session:" + event.getSession().getId() );
    
        }
    
        public void registerSession() {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put( "sessionBindingListener", this  );
            log.info( "registered sessionBindingListener"  );
        }
    
        public void valueUnbound(HttpSessionBindingEvent event) {
            log.info("valueUnBound:" + event.getName() + " session:" + event.getSession().getId() );
                   // add you unlock code here:
            clearLocksForSession( event.getSession().getId() );
        }
    }
    
    0 讨论(0)
提交回复
热议问题