28

What's the best way to set an expiration date for the JSESSIONID cookie sent by Tomcat for a servlet session?

By default, the expiration date of the cookie seems to be 'session', which means that the session disappears in the client as soon as the browser restarts. But I would like to keep it open for 12h, even after a browser restart (and would then configure the session timeout in the server accordingly).

Is there any way to set an expiration date within Tomcat, e.g. using some configuration option or extension module? Or is there a reliable way to set an expiration date for JSESSIONID using a Servlet filter?

Tim Jansen
  • 3,220
  • 2
  • 22
  • 27

2 Answers2

60

As of Servlet 3.0, this can simply be specified in the web.xml:

<session-config>
    <session-timeout>720</session-timeout> <!-- 720 minutes = 12 hours -->
    <cookie-config>
        <max-age>43200</max-age> <!-- 43200 seconds = 12 hours -->
    </cookie-config>
</session-config>

Note that session-timeout is measured in minutes but max-age is measured in seconds.

Mark Amery
  • 110,735
  • 57
  • 354
  • 402
Sander
  • 616
  • 6
  • 2
  • This doesn't help, since Tomcat doesn't resend the jsession-id on each request. So even if the user sends subsequent requests, the tomcat session is extended but the cookie max-age isn't, causing the user to lose its session despite being active. – Yamcha Dec 27 '17 at 19:27
  • @Yamcha I think you are right, however maybe having an enough big expiration time would result only that the user needs to re-login after every 12 hours, even if he was active at the time. It is not so bad. – peterh Jun 13 '19 at 14:29
-1

I don't think it's possible to do what you want, without changing the Tomcat code.

Note however that it might have a nasty side effect : if a user starts a session and stays active for twelve hours, its session timeout will be updated accordingly (the timeout will be updated at each request), but its cookie won't, and the user will thus lose its session after 12 hours, even if he's been active all this time.

David Sykes
  • 43,314
  • 17
  • 65
  • 77
JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174
  • Sander's answer shows that it is indeed possible, and a quick Google reveals that Servlet 3.0 was released in 2009, suggesting to me that this answer was incorrect at the time it was posted. Thus, -1! – Mark Amery Dec 12 '18 at 14:11