I am building a java web board game using servlets. I need to know when a user is not answering for 30 secundes, I am using
session.setMaxInactiveInterval(30);
But I need to know on the server side once the time ended so I can make this player quite.
As it is now once the player return and try to do something he will get the timeout and I can see on on the server.
How can I know in the servlet once a session has timeout?!
Thank you.
You need to implement the HttpSessionListener
interface. It receives notification events when session is created, or destroyed. In particular, its method sessionDestroyed(HttpSessionEvent se)
gets called when the session is destroyed, which happens after timeout period has finished / session was invalidated. You can get the information stored in the session via HttpSessionEvent#getSession()
call, and later do any arrangements that are necessary with the session. Also, be sure to register your session listener in web.xml
:
<listener>
<listener-class>FQN of your sessin listener implementation</listener-class>
</listener>
If you ultimately want to distinguish between invalidation and session timeout you could use the following line in your listener:
long now = new java.util.Date().getTime();
boolean timeout = (now - session.getLastAccessedTime()) >= ((long)session.getMaxInactiveInterval() * 1000L);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With