Search code examples
javaservletsauthenticationlogoutstripes

timertask-based logout give me problems


In this website I need a system that logs the user out after 10 minutes. In order to login I use a simple procedure of inserting a user (in my case called Lid) instance, and the logout invalidates the session, additionally, when the user logs in a timertask within a timer starts, and after 10 minutes invalidates the session.

Here is the code:

MyTask task = null;

private void setCurrent(String key, Object o) {
    getRequest().getSession().setAttribute(key, o);
}

private <T> T getCurrent(String key) {
    T value = (T) getRequest().getSession().getAttribute(key);
    return value;
}

public void logIn(Lid lid) {
    setCurrent("lid", lid); 
    Timer timer = new Timer();
    task = new MyTask(getRequest().getSession());
    System.out.println(task.toString());
    timer.schedule(task,10*60*1000);
}

public void logOut() {
    task.cancel();
    getRequest().getSession().invalidate();
}

This is the MyTask code:

public class MyTask extends TimerTask {

    HttpSession session = null;

    public MyTask(HttpSession session) {
        this.session=session;
    }

    @Override
    public void run() {
        session.invalidate();
    }

}

The problem is that when I voluntarily log out, it throws an exception because it says that the task variable is null, and so it becomes not possible to call cancel() on the task variable.

But I don't get it, after logging in the variable is instantiated, its not null.

Do you have some advise about this? Thank you


Solution

  • Why not just let the web container handle session time-out for you? If you put below code in your web.xml all inactive sessions will expire in 10 minutes:

    <session-config> 
      <session-timeout>10</session-timeout> 
    </session-config>