如何在会话对象被销毁之前调用方法? [英] How to call a method before the session object is destroyed?
问题描述
开发JSP应用程序时,可以定义会话超时值,比如30分钟。
超时后,会话对象被销毁。
此外,我可以通过编程方式使会话调用session.invalidate()无效。
由于我在HTTP会话中保存了一个复杂的Java对象,因此无效之前会话或让tomcat app服务器过期,我需要调用一个保存的对象方法来释放一些内存。当然,当用户单击注销按钮时,我可以通过编程方式执行此操作。
我想要做的是拦截Tomcat应用服务器什么时候会破坏所有过期的会话(30分钟或自定义),这样我就可以预先处理会话中保存的Java对象,调用特定方法来释放内存。
是否可以?
是的,这是可能的。您可以使用 HttpSessionListener
并在 sessionDestroyed()
方法中完成工作,
@WebListener
公共类MyHttpSessionListener实现HttpSessionListener {
@Override
public void sessionDestroyed(HttpSessionEvent event){
//这里的工作。
}
// ...
}
或你可以让作为会话属性存储的复杂对象实现 HttpSessionBindingListener
并在 valueUnbound()$ c $中完成工作c>方法。
公共类YourComplexObject实现HttpSessionBindingListener {
@Override
public void valueUnbound(HttpSessionBindingEvent事件){
//在这里完成工作。
}
// ...
}
每当要从会话中删除对象时(通过 HttpSession#removeAttribute()
或通过会话的无效/过期)将调用它。 / p>
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?
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).
这篇关于如何在会话对象被销毁之前调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!