Since this question came close to the ideas of 5 thousand, I think it would be useful to provide an example of a working solution.
The approach described in the question is incorrect - it will not handle server reboots and will not scale. Here is the best approach.
Firstly, your HttpServlet should handle user logins and logins, something like these lines:
public class ExampleServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter("do"); HttpSession session = req.getSession(true);
The bean user must be Serializable and must re-register when de-serializing:
class User implements Serializable { private String sessionId; private String login; User(String sessionId, String login) { this.sessionId = sessionId; this.login = login; } public String getLogin() { return login; } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject();
You will also need an HttpAttributeListener to properly manage the session life cycle:
public class UserAttributeListener implements HttpSessionAttributeListener { static Map<String, User> sessions = new ConcurrentHashMap<>(); @Override public void attributeAdded(HttpSessionBindingEvent event) { if ("user".equals(event.getName())) sessions.put(event.getSession().getId(), (User) event.getValue()); } @Override public void attributeRemoved(HttpSessionBindingEvent event) { if ("user".equals(event.getName())) ExampleServlet.sessions.remove(event.getSession().getId()); } @Override public void attributeReplaced(HttpSessionBindingEvent event) { if ("user".equals(event.getName())) ExampleServlet.sessions.put(event.getSession().getId(), (User)event.getValue()); } }
Of course, you will need to register your listener in web.xml:
<listener> <listener-class>com.example.servlet.UserAttributeListener</listener-class> </listener>
After that, you can always access the static map in the UserAttributeListener to get an idea of how many sessions are running, how many sessions each user is using, etc. Ideally, you will have a slightly more complex data structure requiring a separate singleton class with proper access methods. Using containers with a copy-on-write strategy at the same time can also be a good idea, depending on the use case.