Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session Lost when closing the browser

I setup my Session time out.

 <session-config>
<session-timeout>11520</session-timeout>

</session-config>

Each time when I close the browser and open it again by calling the servlet, I see that new session is created. It can be seen from SessionCreated method executed in HttpSessionListener each time when browser reopened.

I'm new in tomcat/Java, but if I were working in ASP.NET environment, I would work around it be setting cookie with the same name as session name.

What is the best practice to work around it in Tomcat?

thank you in advance.

Danny.

like image 339
danny.lesnik Avatar asked Sep 11 '10 23:09

danny.lesnik


People also ask

Is session destroyed when browser is closed?

Browsers deletes the session cookies when the browser is closed, if you close it normally and not only kills the process, so the session is permanently lost on the client side when the browser is closed.

Does session expire on closing tab?

Closing a tab/window ends the session and clears objects in sessionStorage .

How do I remove session variables in browser?

session_unset just clears out the session for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists. session_unset just remove all session variables.


2 Answers

I found out, in a similar question, that this is now supported in Servlet 3.0:

<session-config>
  <session-timeout>11520</session-timeout>
  <cookie-config>
    <max-age>11520</max-age>
  </cookie-config>
</session-config>

(A little bit late but I hope this can be useful for someone else too)

like image 190
tyrion Avatar answered Sep 26 '22 04:09

tyrion


Each time when I close the browser and open it again by calling the servlet, I see that new session is created.

That's conform the specified behaviour. The session cookie doesn't have an age, so it lives as long as the client has the webbrowser instance open or until the client hasn't visited the website for long as specified in the session-timeout setting in the server side.

You basically want a cookie which lives longer than the session cookie. You can create a new long-living cookie using Cookie API, set its age using Cookie#setMaxAge(), add it to the HTTP response using HttpServletResponse#addCookie(). On the subsequent HTTP requests you can determine the presence of the cookie using HttpServletRequest#getCookies().

This is by the way not Tomcat specific. You can do the same on every other servletcontainer.

like image 39
BalusC Avatar answered Sep 22 '22 04:09

BalusC