gpt4 book ai didi

java - 如果存在 session 超时,则从数据库中删除java

转载 作者:行者123 更新时间:2023-12-01 18:45:06 25 4
gpt4 key购买 nike

我需要能够在 session 超时时自动注销我的用户,方法是删除表中的记录,在该表中,用户每次登录时都会输入用户详细信息,并在注销期间删除。有没有一种方法可以自动执行此操作而无需用户交互?

类似这样的事情:

HttpSession session = request.getSession(false);
LogoutBean lgub = new LogoutBean();
LogoutDao lgud = new LogoutDao();
if(session == null){
lgud.logoutUser(lgub);
}

我应该在哪里放置代码,以便在 session 超时时用户会注销?

最佳答案

使用 HttpSessionListener

@WebListener
public class LogoutListener implements HttpSessionListener {
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
// I don't know which user you are logging out here (you probably want to get some data from session)
LogoutBean lgub = new LogoutBean();
LogoutDao lgud = new LogoutDao();
// don't need to check if session is null (it obviously isn't at this point, it's being destroyed)
lgud.logoutUser(lgub);
}

// sessionCreated() goes here
}

但请注意,当 session 超时时,并不能保证立即发生这种情况。它可能会在以后随时发生。这取决于某个预定的 servlet 容器线程。

您可以使用 Servlet 3.0 @WebListener 或在 web.xml 中声明监听器:

<listener>
<listener-class>your.domain.listeners.LogoutListener</listener-class>
</listener>

关于java - 如果存在 session 超时,则从数据库中删除java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18129798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com