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?

1
  • have you tried cookie.setMaxAge! Commented Dec 28, 2014 at 9:19

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

On which cookie? I didn't create the cookie manually it is automatically created by the servlet.
Overwriting the cookie worked, thank you!
I'm having double cookie right now :/: I've got two cookies named: JSESSIONID
One that expires when the browser closes and one that I've set manually. However when I then restart the browser, only the one I set manually 'survives'. Is this bad that I've got double cookie?
The best answer in all the internet: simple and clean. Thank you!
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

4 Comments

Okay, but why does my github account stays logged in? Do they use something different?
Check your webapp's cookie and check github's cookie then restart browser and check both again
Hmm yeah it seems like it deletes the cookies. But how does facebook/google/github etc handle these problems?
login to google's account, see their cookie, and do a diff with your webapp's coookie, restart browser and compare them again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.