Search code examples
sessionstruts2server-sidedispose

Dispose session objects


Is it possible to dispose of objects that are stored in the session in struts2?

Some of the objects I would like to store in the session have resources that need to be released, but I can't find a way to dispose of them cleanly when the session times out or is closed.

I realize that client-based solutions require a javascript timer, but I'm not worried about the client side right now. I just want to be able to clean the resources up on the server-side when the session times out.

I thought about checking the sessions (plural because there can be many concurrent sessions with different clients) on each request and performing late cleanup, but at that point the session map is already gone.


Solution

  • Found the answer from a coworker. Thanks for the suggestions.

    It appears the solution is to create a class that implements HttpSessionListener. This interface contains functions that are called when the session is created and destroyed. Then add:

    <listener>
        <listener-class>my.package.listeners.TestSessionListener</listener-class>
    </listener>
    

    To web.xml or your servlet configuration file.