当然有不止一种方法,我的第一个想法是将会话挂接到ServletContext。类似的东西
// this can be in some util class, let's call it SessionUtil
static final String SESSION_REGISTER = "session.register";
public static synchronized void registerSession(ServletRequest req, HttpSession ses, String userName) {
ServletContext ctx = req.getServletContext();
Map<String, List<HttpSession>> register = (Map<String, List<HttpSession>>) ctx.getAttribute(SESSION_REGISTER);
if (register == null) {
register = new HashMap<>();
ctx.setAttribute(SESSION_REGISTER, register);
}
List<HttpSession> sessions = register.computeIfAbsent(userName, k -> new ArrayList<>());
sessions.add(ses);
}
然后,在你的代码中,你需要在登录后注册用户的会话:
HttpSession ss = request.getSession();
if (isUser(name,password)) {
ss.setAttribute("user",name)
SessionUtil.registerSession(request, ss, name);
}
最后,您需要一个方法(同样在SessionUtil 类中)使所有用户的会话(当前会话除外)无效:
public static synchronized void invalidateSessions(ServletRequest req, HttpSession current, String userName) {
ServletContext ctx = req.getServletContext();
Map<String, List<HttpSession>> register = (Map<String, List<HttpSession>>) ctx.getAttribute(SESSION_REGISTER);
if (register != null) {
List<HttpSession> sessions = register.get(userName);
if (sessions != null) {
for (HttpSession ses : sessions) {
if (!ses.equals(current)) {
ses.invalidate();
}
}
}
}
}
然后您可以调用此方法,例如当用户更改他/她的密码时。
注意 #1: 不是一个很好的代码,它错过了一些健全性检查,synchronized 可以是更小的代码块。只是给你一个想法。
注意#2:registerSession(...)方法的功能可以使用HttpSessionAttributeListener来完成,但我还没用过,所以不能举个例子。