AFAIK, the httpsessionlisterner implementation listener class is get instantiated when the first session is created.
Therefore, i would like access this instance because i need to count how many active session and display it some where and i would like to check which user is currently login. In the code below, there is list instance variable, i need to access this listener class in order to access the private variable.
@WebListener()
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {
private List<HttpSession> sessionList;
public SessionListener() {
sessionList = new ArrayList<HttpSession>();
}
@Override
public void sessionCreated(HttpSessionEvent se) {
sessionList.add(se.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
sessionList.remove(se.getSession());
}
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
}
/**
* @return the sessionList
*/
public List<HttpSession> getSessionList() {
return Collections.unmodifiableList(sessionList);
}
Please help.
Thanks.
I have to make a few assumptions as you don’t say how your authentication method works.
I will assume that your username will be contained in your HttpServletRequest (this is very common). Unless you have specifically coded your session to contain the username it will not contain the username of the authenticated user – the username is usually confined to the HttpServletRequest. Therefore you will not usually achieve your goal by using an HttpSessionListener. You probably know this but there are various “scopes”.
As I said, the username is usually stored in the request scope. You can access the session and application scopes from the request scope. You cannot access the request scope from the session scope (as this doesn’t make sense!).
To solve your problem I would create a Map stored in the application scope and use a ServletFilter to populate it. You might want to use a time based cache (using the session time-out value) rather than a straight map as mostly sessions are started but timeout rather than get explicitly terminated by the user. kitty-cache is a really simple time based cache that you could use for this purpose.
Anyway a code sketch (untested) might look something like this:
You should now be able to obtain details of who and how many users are logged in from the authsessions Map that is stored in the application scope.
I hope this helps,
Mark
UPDATE
In which case a HttpSessionListener might work for you – although as I mentioned before you probably still need to use a time based cache due to the way that most user sessions timeout rather than terminate. My untested code sketch would now look something like this: