Search code examples
sessionservletscache-control

What is the difference between setting HTTP session timeout using web.xml and setMaxInactiveInterval()


I have a requirement, when an user is authenticated into a session, and after 10 minutes of inactivity, the session times out. Once the session timed out, any further requests are expired, the request is redirected to a timed out page. I have researched in this regard and came to 2 different approaches.

Approach #1:

In web.xml I have the code mentioned below...

<session-config>
     <session-timeout>10</session-timeout>
</session-config>

Approach #2:

I have the code mentioned below inside the authenticated page...

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
request.getSession().setMaxInactiveInterval(600);

Now, my questions are:

What is the difference between these two approaches? Which one is better or recommended?

And also, when using approach #2, if the end user navigates away from the authenticated page, but has not logged out, does the session still times out after 10 mins of inactivity?


Solution

  • Session timeout can be set on various levels:

    • In the application server there is usually default settings, that can be changed - it is a default for all applications, or for given application (depending on server config capabilities).
    • Then in the application descriptor - you can override it by using web.xml - it will be used for all sessions in the given application
    • Then in the application code - you can override it using session.setMaxInactiveInterval(), it will be overridden only for that session

    As Roman wrote:

    no matter how you set it, it is invalidated by the container when timeout expires.

    You should rather avoid programmatic approach (last one), as it is easy to miss some session and it will get the default timeout, and you will have inconsistent behavior. Use web.xml if you want to ensure given timeout (business requirement) and don't want to rely on server capabilities.