How to clear servlet context in Java [duplicate]
I use the servlet context to hold details of logged in users in a hash map. How can I clear the user id of a user who is idle after 20 minutes?
Probably you could set the Session Timeout to 20 minutes for the application, and make sure that each user has a active session, which also contains the user id. If the user goes idle for 20 minutes, then the session will be destroyed.
Then, you can write a HttpSessionListener to get called when a session gets destroyed. From that you can get the user id (which you already stored before, probably when the user logged in), and remove it also from your HashMap with in the SessionContext.
Use servlet session management for invalidating the sessions. This below snippet in web.xml will invalidate the session if idle for 20 mins.
<session-config><session-timeout>20</session-timeout></session-config>
Implement javax.servlet.http.HttpSessionListener.sessionCreated() to get a callback when a session is created. Add this session id to the servlet context using
List<String> users = HttpSessionEvent.getSession().getServletContext().getAttribute("users");
users.add(session.getId());
Implement javax.servlet.http.HttpSessionListener.sessionDestroyed() which gets a callback when a session is destroyed. Remove this session from the servlet context using
List<String> users = HttpSessionEvent.getSession().getServletContext().getAttribute("users");
users.remove(session.getId());
The simplest way is to implement ServletContextListener
, in contextInitialized()
start a thread that will do the work. in contextDestroyed
shudown the thread. The Map should be threadsafe: synchronized or Concurrent.
- Schedule a job from
ServletContextListener
- use
remove()
method ofHashMap
simply , make sure aboutconcurrency
精彩评论