开发者

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

开发者 https://www.devze.com 2023-04-12 23:59 出处:网络
When developing a JSP application it\'s possible to define a session ti开发者_JAVA百科meout value, say 30 minutes.

When developing a JSP application it's possible to define a session ti开发者_JAVA百科meout 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消