How to iterate and get all user name from session
I am using tomcat server. When the application has to access by multiple users. all user details are stored in sess开发者_Go百科ion only. In some situation I have to get all user's detail. How can iterate and get all users detail from that session.
Just collect and store all logins in the application scope then. Easiest would be to let the User
object which represents the logged-in user implement HttpSessionBindingListener
. You only need to prepare a Set<User>
in the application scope (as a ServletContext
attribute).
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);
}
// Don't forget to override equals() and hashCode() as well.
}
This way, whenever you login the user as follows
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
// ...
}
then the valueBound()
will be called. Whenever you logout the user by removing the attribute or invalidating the session or let the session expire, then valueUnbound()
will be called.
The ServletContext
attribute is of course just available in all servlets and JSPs.
精彩评论