独立于 DB 的方法是让 有一个变量并实现 HttpSessionBindingListener
(和 Object#equals()
和 Object#hashCode()
)。这样,您的web应用程序在不可预见的崩溃后仍将运行,这可能会导致数据库值无法更新(您当然可以创建一个在webapp启动时重置数据库,但这只会越来越多)。User
static Map<User, HttpSession>
ServletContextListener
下面是 应如下所示:User
public class User implements HttpSessionBindingListener {
// All logins.
private static Map<User, HttpSession> logins = new ConcurrentHashMap<>();
// 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 user = userDAO.find(username, password);
if (user != null) {
sessionMap.put("user", user);
} else {
// Show error.
}
然后它将调用,这将从地图中删除任何先前登录的用户并使会话无效。valueBound()
logins
当您注销时,如下所示:User
sessionMap.remove("user");
或者当会话超时时,将调用 ,这将从映射中删除用户。valueUnbound()
logins