开发者

How to clear servlet context in Java [duplicate]

This question already has answers here: 开发者_如何学运维 How to run a background task in a servlet based web application? (5 answers) Closed 7 years ago.

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 of HashMap simply , make sure about concurrency
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜