Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

When developing a JSP application it's possible to define a session timeout value, say 30 minutes.

After that timeout, the session object is destroyed. Moreover I can programmatically invalidate a session calling session.invalidate() .

Since I'm saving a complex Java object inside the HTTP session, before invalidate the session or let it expire by the tomcat app server, I need to call a saved object method to release some memory. Of course I can do it programmatically when the user click a logout button.

What I would like to do is intercepting the Tomcat app server when it is going to destroy all expired sessions (30 minutes or custom), so that I can pre-process Java objects saved in the session calling a specific method to release memory.

Is it possible?

like image 754
Cristian D'Aloisio Avatar asked Oct 13 '11 14:10

Cristian D'Aloisio


People also ask

Which method destroys session object?

The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.

How do you explicitly destroy a session object?

You can set session variables in usual way using string as a key e.g. Session["Key"] = obj; To destroy the object in Session set it to null. Session["Key"] = null. you can clear the user session through the session.

How can an existing session in servlet can be destroyed?

Once the user requests to logout, we need to destroy that session. To do this, we need to use invalidate() method in HttpSession Interface.

How do you destroy a specific session in Java?

Full Stack Java developer - Java + JSP + Restful WS + Spring Delete the whole session − You can call the public void invalidate() method to discard an entire session. Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.


1 Answers

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).

like image 95
BalusC Avatar answered Nov 28 '22 06:11

BalusC