我需要知道登录用户的 Activity session 数。通过 HttpServletRequest ,我可以检索当前登录的主体 -> getUserPrincipal() 。有没有办法查询该主体的 Activity session 数?
最佳答案
我不认为 servlet Api 提供这个。但你可以通过功能来做到这一点。
创建用户和 session 对象的映射。
Map<User, HttpSession> logggedUserMap = new HashMap<User, HttpSession>();
在用户登录时添加条目,并在注销时将其删除。
所以logggedUserMap.size()
值是打开的用户 session 总数。
使用HttpSessionBindingListener ,它将跟踪代码 session 属性中绑定(bind)或未绑定(bind) session 的任何位置。
创建类
class SessionObject implements HttpSessionBindingListener {
String message = "";
User loggedInUser;
Logger log = Logger.getLogger(SessionObject.class);
public SessionObject(User loggedInUser) {
this.loggedInUser=loggedInUser;
}
public void valueBound(HttpSessionBindingEvent event) {
log.info("=========in valueBound method==============");
HttpSession session =LoggedInUserSessionUtil.getLogggedUserMap().get(loggedInUser);
try{
if (session != null && session.getLastAccessedTime() != 0) {
message = "ALL_READY_LOGGEDIN";
return;
}
}catch(IllegalStateException e){
e.printStackTrace();
session = LoggedInUserSessionUtil.removeLoggedUser(loggedInUser);
}
System.out.println("*************************************"+event.getSession().getId() +"------"+loggedInUser+"*********************************************");
log.info("=========valueBound putting in user map==============");
LoggedInUserSessionUtil.getLogggedUserMap().put(loggedInUser, event.getSession());
return;
}
public void valueUnbound(HttpSessionBindingEvent event) {
// This work already doing in Force logout servlet
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
并在用户登录时绑定(bind)此对象实例。
SessionObject sessionObj = new SessionObject(loggedInUser);
req.getSession().setAttribute("Binder.object",sessionObj);
关于java - 从 ServletContainer 或 ApplicationServer 检索打开的 session 数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16919210/