If you just want the no. of sessions, you need to have a static field in HttpSessionListener then take a variable and increment it in sessionCreated and decrement in sessionDestroyed.
Here's a code from xyzws.com
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
public class SessionCounter implements HttpSessionListener {
private static int activeSessions = 0;
public void sessionCreated(HttpSessionEvent se)
{
activeSessions++;
}
public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}
public static int getActiveSessions() {
return activeSessions;
}
}
in web.xml:
<!-- Listeners -->
<listener>
<listener-class>com.xyzws.web.utils.MySessionCounter</listener-class>
</listener>
To display the same:
<html>
...
Active Sessions : <%= SessionCounter.getActiveSessions() %>
...
</html>
Also read this answer on SO.
EDIT:An alternative could be to use ArrayList
for storing userIds,
Firstly you need to set the userId of the user in a session variable whenever a user logs in(You can use different approaches for this).
public class getSessions implements HttpSessionListener
{
ArrayList al=new ArrayList();
public void sessionCreated(HttpSessionEvent se)
{
al.add(uid);
}
public static void getActiveSessions()
{
Iterator itr=al.addIterator();
while(itr.hasNext())
{
System.out.println(itr.next());//or whatever you want to do
}
}
}