arnehehe
arnehehe

Reputation: 1398

Expire all active sessions at the same time, daily

For a Java JSP web application I'm making, I keep an object in a session. If there are multiple users signed onto the site, each in their own session, I would like for all the session (regardless of when they started) to expire at midnight the same day.

For instance:

session object 1: creation date (2012-12-11 8:45), expiration date (2012-12-12 0:00)

session object 2: creation date (2012-12-11 12:00), expiration date (2012-12-12 0:00)

And so on, every day the day's sessions getting invalidated.

Some ideas I had was

What is the best way to go about this?

Upvotes: 1

Views: 430

Answers (2)

Subbu
Subbu

Reputation: 86

The best way I see is Option 2

  1. Implement a HttpSessionListener - http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpSessionListener.html - this will help you collect the active sessions in a Collection using call back methods sessionCreated() and sessionDestroyed().
  2. Use a TimerTask - http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html that runs every midnight and closes all the active sessions you have collected.

Option 1 is also possible but might be little unpredictable as you have to set a precise timeout every time you create a new session.

Have fun !

Upvotes: 3

sp00m
sp00m

Reputation: 48817

Set the expiration date of the sessions at the end of the current day:

Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 23);
today.set(Calendar.MINUTE, 59);
today.set(Calendar.SECOND, 59);
Date expiration = today.getTime();

Upvotes: 0

Related Questions