5

I'm working on a small project with java servlets/jstl

I've created a login with a session and I want the browser to keep that session even after a browserrestart.

I've written this code:

HttpSession session=request.getSession();
session.setMaxInactiveInterval(604800);
session.setAttribute("loggedOnUser", true);

I've set the session timeout to a week. But whenever I close the browser and reopen it I need to login again. When I look at the cookies of my browser, the cookie that contains the sessionId still expires when the browser closes. I thought "setMaxInactiveInterval" would change that to one week. Does anyone know what the problem is?

jmj
  • 237,923
  • 42
  • 401
  • 438
Bosiwow
  • 2,025
  • 3
  • 28
  • 46

2 Answers2

5

I suggest setting the max-age of that cookie:

HttpSession session = request.getSession();
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(cookie);
Anirudha
  • 32,393
  • 7
  • 68
  • 89
1

when browser restarts some browser deletes cookies and that is why when after restart when you make new request server doesn't see cookie in request and treats it as a new session

jmj
  • 237,923
  • 42
  • 401
  • 438
  • Okay, but why does my github account stays logged in? Do they use something different? – Bosiwow Dec 28 '14 at 09:16
  • Check your webapp's cookie and check github's cookie then restart browser and check both again – jmj Dec 28 '14 at 09:18
  • Hmm yeah it seems like it deletes the cookies. But how does facebook/google/github etc handle these problems? – Bosiwow Dec 28 '14 at 09:20
  • login to google's account, see their cookie, and do a diff with your webapp's coookie, restart browser and compare them again – jmj Dec 28 '14 at 09:21