我的网络应用程序有登录的用户。有一个超时。在会话过期之前,我想执行一个方法来清理一些锁。
我已经实现了sessionListener
但一旦我到达public void sessionDestroyed(HttpSessionEvent event)
会话已经消失,我需要从中获取一些数据,所以我想执行一个方法(需要会话处于活动状态并且能够访问FacesConfig.getCurrentInstance()
)在会话实际过期之前。
我怎样才能做到这一点?有任何想法吗?这是我的会话监听器:
public class MySessionListener implements HttpSessionListener {
private static final Logger log = LoggerFactory.getLogger(MySessionListener.class);
public MySessionListener() {
}
public void sessionCreated(HttpSessionEvent event) {
log.debug("Current Session created : "
+ event.getSession().getId()+ " at "+ new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
// get the destroying session...
HttpSession session = event.getSession();
prepareLogoutInfoAndLogoutActiveUser(session);
log.debug("Current Session destroyed :"
+ session.getId()+ " Logging out user...");
/*
* nobody can reach user data after this point because
* session is invalidated already.
* So, get the user data from session and save its
* logout information before losing it.
* User's redirection to the timeout page will be
* handled by the SessionTimeoutFilter.
*/
// Only if needed
}
/**
* Clean your logout operations.
*/
public void prepareLogoutInfoAndLogoutActiveUser(HttpSession httpSession) {
UserBean user = FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{user}", UserBean.class);
LockBean lock = FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{lock}", LockBean.class);
lock.unlock(user.getUsername());
log.info("Unlocked examination for user: "+user.getUsername());
}
}
但我越来越NullPointerException
at FacesContext.getCurrentInstance().getApplication()
因为要么getCurrentInstance
为空或getApplication
返回空值
您可以通过实现 HttpSessionBindingListener 来实现这一点,您需要通过调用来注册一个持有锁的会话registerSession
(字符串“sessionBindingListener”不能更改)。容器会回调valueUnbound()
会话超时后的方法和before会话被破坏。
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() );
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)