I want to know if the user's session has expired in the server side and perform something when that happens. How do I do this?
I'm using Java and Play framework 2.2.1.
To prevent a session timeout, you must interact with the workbook. This might include navigation around the workbook, sorting, filtering, or any other activity that you do with the elements of the workbook. When the server detects user interaction with the workbook, it keeps the session active.
Session timeout represents the event occuring when a user does not perform any action on a web site during an interval (defined by a web server). The event, on the server side, changes the status of the user session to 'invalid' (ie.
The session inactivity timeout setting represents the amount of time a user can be inactive before the user's session times out and closes. It only affects user browser sessions. You can set the values from 5 minutes to 60 minutes. This function has a default value of 30 minutes.
When using Play's built-in authentication, at every authenticated request, store a timestamp in the session with the updated expiration.
Then, in the authenticator, validate the session expiration.
The article How to implement a Session Timeout in Play Framework 2 offers this example:
public class Secured extends Security.Authenticator {
public static final String UNAUTHENTICATED = "unauthenticated";
public static User getLoggedInUser() {
if (session("userId") == null)
return null;
return User.findById(Long.parseLong(session("userId")));
}
public static String getLoggedInUsername() {
if (session("userId") == null)
return null;
return User.findById(Long.parseLong(session("userId"))).getUsername();
}
@Override
public String getUsername(Http.Context ctx) {
// see if user is logged in
if (session("userId") == null)
return null;
// see if the session is expired
String previousTick = session("userTime");
if (previousTick != null && !previousTick.equals("")) {
long previousT = Long.valueOf(previousTick);
long currentT = new Date().getTime();
long timeout = Long.valueOf(Play.application().configuration().getString("sessionTimeout")) * 1000 * 60;
if ((currentT - previousT) > timeout) {
// session expired
session().clear();
return null;
}
}
// update time in session
String tickString = Long.toString(new Date().getTime());
session("userTime", tickString);
return User.findById(Long.parseLong(session("userId"))).getUsername();
}
}
This requires a sessionTimeout
value in minutes in the application's configuration file (application.conf
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With