Stanley Mungai
Stanley Mungai

Reputation: 4150

Delete from database if there is Session timeout java

I need to be able to logout my users automatically when there is a session timeout by deleting their record in table where user details are entered every time he/she logs in and deleted during logout. Is there a way to do this automatically without user interaction?

Something like this:

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

And where do I place the code so that if there is a session timeout, the user is logged out?

Upvotes: 0

Views: 961

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

Use an 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
}

Note however that this is not guaranteed to happen immediately when the session does timeout. It can happen any time later. It's up to some scheduled servlet container thread.

You can declare the listener either with Servlet 3.0 @WebListener or in web.xml as

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

Upvotes: 4

Related Questions