Show remaining session time

Asked

Viewed 2,215 times

4

I am working with JSP and Servlet. I want to show on the jsp page the remaining time to expire the session I set in my web.xml:

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

Has anyone ever done anything like this?

2 answers

2

You can use the method getLastAccessedTime() that returns the time (in milliseconds) of the last session-associated request.

And then use the method getMaxInactiveInterval() to obtain the maximum time interval (in seconds) that the container will keep this session open.

Having these two values, simply subtract the session time by the time of the last request, remembering that one method returns the value in milliseconds while the other returns in seconds:

Long segundos = session.getMaxInactiveInterval() -
                (System.currentTimeMillis() - session.getLastAccessedTime()) / 1000;

The conversion, for minutes for example, can be done by means of an object TimeUnit:

long minutosRestantes = TimeUnit.SECONDS.toMinutes(segundos);
out.print(minutosRestantes); // Exibe o tempo (em minutos) restante

1

With the Httpsession class (represented by the implicit object session in JSP) you can recover the time of last access through the method getLastAccessedTime() that will return time in milliseconds, so you can manipulate it using some date class with Calendar or Date

Browser other questions tagged

You are not signed in. Login or sign up in order to post.