How to call a method before the session object is destroyed?

Solution 1:

Yes, that's possible. You could use HttpSessionListener and do the job in sessionDestroyed() method,

@WebListener
public class MyHttpSessionListener implements HttpSessionListener {

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        // Do here the job.
    }

    // ...
}

Or you could let the complex object which is been stored as a session attribute implement the HttpSessionBindingListener and do the job in valueUnbound() method.

public class YourComplexObject implements HttpSessionBindingListener {

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        // Do here the job.
    }

    // ...
}

It will be called whenever the object is to be removed from the session (either explicitly by HttpSession#removeAttribute() or by an invalidation/expire of the session).