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

时间:2013-08-08 15:16:51

标签: java session servlets

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

这样的事情:

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

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

1 个答案:

答案 0 :(得分: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>