If user close the browser without logout.
特别是这种情况很难,不可靠.您可以在Javascript中使用beforeunload事件,但您完全依赖浏览器是否启用了JS,特定浏览器支持此非标准事件(例如Opera不支持).这也是我建议只是注销以前登录的用户而不是防止登录的主要原因之一.对于用户“忘记”从其他计算机注销的情况,这也更加用户友好和安全.
public class User implements HttpSessionBindingListener {
// All logins.
private static Map logins = new HashMap();
// Normal properties.
private Long id;
private String username;
// Etc.. Of course with public getters+setters.
@Override
public boolean equals(Object other) {
return (other instanceof User) && (id != null) ? id.equals(((User) other).id) : (other == this);
}
@Override
public int hashCode() {
return (id != null) ? (this.getClass().hashCode() + id.hashCode()) : super.hashCode();
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
HttpSession session = logins.remove(this);
if (session != null) {
session.invalidate();
}
logins.put(this, event.getSession());
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
logins.remove(this);
}
}
当您登录用户时,如下所示:
User user = userDAO.find(username, password);
if (user != null) {
request.getSession.setAttribute("user", user);
} else {
// Show error.
}
那么它将调用valueBound(),它将从登录映射中删除任何先前登录的用户,并使会话无效.
当您注销用户时,如下所示:
request.getSession().removeAttribute("user");
或者当会话超时时,将调用valueUnbound(),从用户登录映射中删除该用户.