Starting a session when closing the browser

I set the session time of the session.

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

</session-config>

Each time I close the browser and open it again, invoking the servlet, I see that a new session has been created. This can be seen from the SessionCreated method executed in the HttpSessionListener each time the browser is reopened.

I am new to tomcat / Java, but if I were working in ASP.NET, I would work on setting a cookie with the same name as the session name.

What is the best practice for working at Tomcat?

thank you in advance.

Danny

+7
java cookies tomcat servlets session
source share
2 answers

Each time I close the browser and open it again, invoking the servlet, I see that a new session has been created.

This is consistent with the specified behavior. The session cookie is age-free, so it lives until the client opens a web browser instance or until the client visits the website for a long time, as specified in the session-timeout parameter on the server side.

You basically want a cookie that lasts longer than a session cookie. You can create a new long-lived cookie using the Cookie API, set its age using Cookie#setMaxAge() , add it to your HTTP response using HttpServletResponse#addCookie() . In subsequent HTTP requests, you can determine whether a cookie HttpServletRequest#getCookies() using HttpServletRequest#getCookies() .

This, by the way, is not Tomcat. You can do the same on any other servlet server.

+9
source share

I found out in a similar question what 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 late, but I hope this can be useful for someone else as well)

+9
source share

All Articles