简体   繁体   English

关闭浏览器时会话丢失

[英]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. 每次当我关闭浏览器并通过调用servlet再次打开它时,我看到创建了新会话。 It can be seen from SessionCreated method executed in HttpSessionListener each time when browser reopened. 每次重新打开浏览器时,都可以从HttpSessionListener中执行的SessionCreated方法中看到。

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. 我是tomcat / Java的新手,但如果我在ASP.NET环境中工作,我会解决它设置与会话名称相同的cookie。

What is the best practice to work around it in Tomcat? 在Tomcat中解决它的最佳实践是什么?

thank you in advance. 先感谢您。

Danny. 丹尼。

I found out, in a similar question , that this is now supported in Servlet 3.0: 在类似的问题中 ,我发现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) (有点晚了,但我希望这对其他人也有用)

Each time when I close the browser and open it again by calling the servlet, I see that new session is created. 每次当我关闭浏览器并通过调用servlet再次打开它时,我看到创建了新会话。

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. 会话cookie没有年龄,因此只要客户端打开了webbrowser实例,或者客户端没有按照服务器端的session-timeout设置中的指定长时间访问网站,它就会存在。

You basically want a cookie which lives longer than the session cookie. 你基本上想要一个比会话cookie更长寿的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() . 您可以使用Cookie API创建一个新的长寿命cookie,使用Cookie#setMaxAge()设置其年龄,使用HttpServletResponse#addCookie()将其添加到HTTP响应中。 On the subsequent HTTP requests you can determine the presence of the cookie using HttpServletRequest#getCookies() . 在随后的HTTP请求中,您可以使用HttpServletRequest#getCookies()确定cookie的存在。

This is by the way not Tomcat specific. 顺便说一句,这不是Tomcat具体的。 You can do the same on every other servletcontainer. 您可以在每个其他servlet容器上执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM