HttpSessionListener - Will sessionDestroyed method

2019-04-07 14:32发布

问题:

This question already has an answer here:

  • How to call sessionDestroyed when a session times out 4 answers

I have an implementation of HttpSessionListener where 'locked' resources in the application are released with sessionDestroyed method.

The 'lock' information is maintained in database, and the release of locks is working fine in most cases. But In some cases I still see resource is locked - even if there is no session active!

So, I'm doubting if there is possibility that sessionDestroyed not being invoked? Suppose if the session is timed out - will sessionDestroyed method be called?

Suppose user closes browser tab without logging out(destroying session) -then will the listener be invoked?

Thanks in advance!

回答1:

A servlet engine will handle session timeouts. It will determine on its own when the session is no longer valid and it will call the sessionDestroyed. (this can occur some time after the user closed his browser).

Some other points :

Logging

Perhaps you can add some logging to sessionCreated and sessionDestroyed methods. for each sessionCreated you should have a sessionDestroyed.

Excepion Handling

Perhaps the fact that stuff remains locked is not due to the session not being destroyed, but perhaps due to an error in your sessionDestroyed logic. Do you have sufficient exception handling / logging in place there ?

Timing

Did you wait long enough to check your locked resources ? (close all clients, and take into account the session timeout value configured on the application / server). As stated earlier, the server cannot detect a user closing a browser, but it does maintain its list of http sessions, and it will destroy them after timeout.



回答2:

So, I'm doubting if there is possibility that sessionDestroyed not being invoked? Suppose if the session is timed out - will sessionDestroyed method be called?

Yes. A session is destroyed when it times out or someone expires it programatically (via HttpSession.invalidate()).

Suppose user closes browser tab without logging out(destroying session) -then will the listener be invoked?

No, because the session is still valid. If said user opens up the website once again, his/her session will still be valid.

From the HttpSessionjavadoc:

Notifications are sent after the binding methods complete. For session that are invalidated or expire, notifications are sent after the session has been invalidated or expired.