views:

54

answers:

1

Hi,

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.

+4  A: 

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.

BalusC
Thank you for your fast response. Can I set max cookie age in web.xml or in HttpSesisonListener sesison created method?
danny.lesnik
Do it in a `Filter`. There you have the `HttpServletReponse` to your hands. You can check if the session is new by `HttpSession#isNew()`.
BalusC