开发者

Detect session timeout in Spring 3/Spring Security 2.0.5

开发者 https://www.devze.com 2023-01-16 12:12 出处:网络
I have a web application running under Spring 3 with SpringSecurity 2.0.5. To present the user the changes to the site since his last visit, I try to register the time when his session is destroyed. T

I have a web application running under Spring 3 with SpringSecurity 2.0.5. To present the user the changes to the site since his last visit, I try to register the time when his session is destroyed. Therefore I registered org.springframework.context.ApplicationListener<HttpSessionDestroyedEvent> and also a javax.servlet.http.HttpSessionListener. The implemented methods work when the user uses the logout link. But when the ses开发者_运维问答sion times out it's as if the events aren't generated.

Am I forgetting to listen to the right events? Or is there nothing fired for the session timeout? Is there any other way to achieve this? Does it depend on a server setting (which is tomcat 6.0.24 btw)?


I don't do Spring, so no wording about this, but the javax.servlet.http.HttpSessionListener should work when implemented and registered properly. You need to register it as a <listener> in the web.xml as follows:

<listener>
    <listener-class>com.example.MyHttpSessionListener</listener-class>
</listener>

Keep in mind that you're testing the session timeout the right way. Closing a webbrowser window for example won't immediately destroy the session on the server side. The session will live as long as the client hasn't sent any HTTP request for 30 minutes. Those 30 minutes are the default session timeout which is configureable by <session-timeout> entry in web.xml.

Also, the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see the sessionDestroyed() method being called after exactly 30 minutes of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

  • How does Servlets, ServletContext, HttpSession, etc work?


I think, DelegatingSessionListener approach may be useful. It already mentioned here:

How to inject dependencies into HttpSessionListener, using Spring?

0

精彩评论

暂无评论...
验证码 换一张
取 消