jsfcookiessession-scope

Cookie is not cleared when closing the browser


I am currently implementing an "auto-login" mechanism in JSF, see

Cookie maxAge always -1

I have tested the following scenario:

A user logs in without "remember me", then directly closes the browser without clicking log-out (if click log-out, cookie's maxAge will be set to 0). Later, if the user loads the page again, in the filter, the cookie is present in the request (normal, because cookie maxAge is not changed to 0 when closing the browser), and the user is automatically logged-in, which is not what I want.

Is there a way to solve this? what is the relation between cookie and session? I use session scope. As what I know, session won't get destroyed when the browser is closed, it is up to the server's decision. Therefore, I can't use @PreDestroy. I can't use Jquery.unload neither, because a user can also close the tab only, not the browser. Also in my application, several tabs can be opened at the same time...

Any suggestions?


Solution

  • You seem to want the cookie live as long as the opened browser instance. I.e. you want the cookie to live as long as the browser session.

    Just make it a session cookie by giving a max age of -1. The cookie will then live as long as the browser instance.

    As to the relationship between HttpSession and cookies, head to How do servlets work? Instantiation, sessions, shared variables and multithreading. Key difference is that the HttpSession has also a server-managed timeout.