我需要能够在会话超时时自动注销我的用户,方法是删除他们在每次登录时输入用户详细信息并在注销时删除用户详细信息的记录。有没有办法在没有用户交互的情况下自动执行此操作?
这样的事情:
HttpSession session = request.getSession(false);
LogoutBean lgub = new LogoutBean();
LogoutDao lgud = new LogoutDao();
if(session == null){
lgud.logoutUser(lgub);
}
我在哪里放置代码,以便在会话超时时,用户退出?
答案 0 :(得分:4)
@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 @WebListener
或web.xml
作为
<listener>
<listener-class>your.domain.listeners.LogoutListener</listener-class>
</listener>