I'm working with JSP and Servlet. I want to display on the jsp page the time remaining to expire the session I set in my web.xml:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Has anyone done anything like this?
I'm working with JSP and Servlet. I want to display on the jsp page the time remaining to expire the session I set in my web.xml:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Has anyone done anything like this?
You can use the getLastAccessedTime()
method that returns the time (in milliseconds) of the last session request.
And then, use the getMaxInactiveInterval()
method to get the maximum time interval (in seconds) that the container will keep this session open.
Having these two values, just 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;
Conversion, for minutes for example, can be done through an object TimeUnit
:
long minutosRestantes = TimeUnit.SECONDS.toMinutes(segundos);
out.print(minutosRestantes); // Exibe o tempo (em minutos) restante
With the HttpSession class (represented by the implicit object session
in the JSP) you can retrieve the last access time using the getLastAccessedTime()
method, which will return the time in milliseconds, so you can manipulate it using some class of dates with Calendar
or Date