Java implementation method for setting session expiration time

  • 2020-04-01 03:32:17
  • OfStack

This article is an example of how to set session expiration time in Java. The specific implementation method is as follows:

1. Timeout in the deployment descriptor (web.xml)
In minutes

<web-app ...>
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>

This setting applies to the entire web application. When the client does not make a request for 20 minutes, the container kills the session.

2. Timeout with setMaxInactiveInterval()
By encoding, specify the expiration time of a particular session in seconds. Such as:

HttpSession session = request.getSession();
session.setMaxInactiveInterval(20*60);

The above setting is only apply on session which calls The "setMaxInactiveInterval()" method, and session will be kill by container if client doesn't make any request after 20 minutes.

Thoughts... .
This is a bit confusing, the value in deployment descriptor (web.xml) is in "the minute", But the setMaxInactiveInterval() method is accept the value in "second". Both functions should synchronize it in future release

3. Defined in the program, the unit is seconds, set to -1 means never expired, and the sample code is:

session.setMaxInactiveInterval(30*60);

The priority for Session Settings to have an effect is to program before configuration, part before whole.

I hope this article has been helpful to your Java programming.


Related articles: