独立于 DB 的方法是让User
有一个static Map<User, HttpSession>
变量并实现HttpSessionBindingListener
(and Object#equals()
and Object#hashCode()
)。这样,您的 webapp 在发生意外崩溃后仍可运行,这可能导致 DB 值未更新(您当然可以创建一个ServletContextListener
在 webapp 启动时重置 DB,但这只是越来越多的工作)。
这是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
地图中删除。