Just collect all logged in users in a Set
in the application scope. If your application is well designed, you should have a javabean User
which represents the logged-in user. Let it implement HttpSessionBindingListener
and add/remove the user from the Set
when it's about to be bound/unbound in the session.
Kickoff example:
public class User implements HttpSessionBindingListener {
@Override
public void valueBound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.add(this);
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.remove(this);
}
// @Override equals() and hashCode() as well!
}
Note that you need to prepare the Set
in the application scope so that it doesn't return null
in above methods. You could do that in the same methods by a nullcheck, or with help of ServletContextListener#contextInitialized()
.
Then, anywhere in your application where you've access to the ServletContext
, like in a servlet, you can just access the logged-in users as follows:
Set<User> logins = (Set<User>) getServletContext().getAttribute("logins");