0

我需要能够在会话超时时自动注销我的用户,方法是删除他们在每次登录时输入用户详细信息并在注销期间删除的表中的记录。有没有办法在没有用户交互的情况下自动执行此操作?

像这样的东西:

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

我在哪里放置代码,以便在会话超时时用户退出?

4

1 回答 1

4

使用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
}

但是请注意,当会话超时时,这并不能保证立即发生。它可以在以后的任何时间发生。这取决于一些预定的 servlet 容器线程。

您可以使用 Servlet 3.0@WebListenerweb.xml作为

<listener>
    <listener-class>your.domain.listeners.LogoutListener</listener-class>
</listener>
于 2013-08-08T15:22:13.130 回答