I have a web based application that uses userName and password for login.
now how can i check on certain time which all users are logged in at that very time. i am using session management and no DB is used in application everything is on filesystem
Edit: 1 more silly doubt.. how to define a variable with application scope.. is this something of this sort?
开发者_JS百科<env-entry>
<env-entry-name>test/MyEnv2</env-entry-name>
<env-entry-type>java.lang.Boolean</env-entry-type>
<env-entry-value>true</env-entry-value>
</env-entry>
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");
Update
BalusC's approch is more suitable, here by this approach you will get no of session not logged in Users. to do that you need to track HttpSessionBindingListener .
You can implement HttpSessionListener
and can track the logged in users
public void sessionCreated(HttpSessionEvent se) {
// adding logging in user to some application data map or inserting it to DB
}
public void sessionDestroyed(HttpSessionEvent se) {
// remove logged in user to some application data map or inserting it to DB
}
A more scaleable solution would be to add a column like "loggedIn" to your users table in the database and set it to true when you log a user in. This would take bloat off the application server and also support a distributed environment if your application needs to run more than one box in the future.
精彩评论