3

I'm writing my SPring MVC web application.

I have set my session time out to be 10080 minutes equal to 1 week. Now I would like to keep user logged in every time he open browser:

sessionService.setcurrentUser(myuser);
      HttpSession session = request.getSession();
      Cookie cookie = new Cookie("JSESSIONID", session.getId());
      cookie.setMaxAge(timeout);
      response.addCookie(cookie);

Should my cookie Max Age be the same as session time out?

cookie.setMaxAge(10080);

Is it good practice?

danny.lesnik
  • 18,479
  • 29
  • 135
  • 200
  • FYI, the setMaxAge parameter value is in seconds, while the session-timeout is in minutes -- you need to multiply 10080 by 60 to get the end-result you're looking for. – Vladimir Feb 19 '12 at 21:13

3 Answers3

7

You should configure it in web.xml, not by hacking the default session cookie.

<session-config>
    <session-timeout>10080</session-timeout>
</session-config>

Note that you shouldn't store too much data in session and/or that your server has enough memory.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • This won't work. By default (at least on Tomcat), a session becomes invalid when the browser is closed. This happens because the age of the session cookie (if applicable) is set to "0". – wh81752 Aug 24 '13 at 09:57
  • @user I answered the question, not the functional requirement. You're right, this answer is inapplicable. I have answered such a question several times before anyway. – BalusC Aug 24 '13 at 12:06
1

You use cookies to refer to your session id. If the timeout of the cookie is lower than the session, it will not find your session anymore. So setting your timeout of your cookie to at least the timeout of your session is advisable.

Roalt
  • 8,330
  • 7
  • 41
  • 53
  • 1
    This answer does not make sense. The id of the session (JSESSIONID) is forwarded to the servlet container via the mechanics of a cookie (alternative via URL rewriting). Thus from a user perspective the session is gone if the cookie times out. If the cookie timeout is higher than the session-idle-timeout (web.xml/session-config/session-timeout) then the container may invalidate a session before the cookies max age has been reached. – wh81752 Aug 24 '13 at 10:13
1

The following posts contain interesting information.
As far as good practice goes you probably have two things to consider:

  • Security aspect of leaving a the session active for a long period of time.
  • Memory implications, your session will be serialized and you want to keep it to a minimum. Especially if the amount of users could grow drastically.

Discussion 1
Discussion 2
Discussion 3

Community
  • 1
  • 1
emt14
  • 4,846
  • 7
  • 37
  • 58