Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

java - How to call sessionDestroyed when a session times out

I am new to JSP. I used the following code in a class that implements HttpSessionListener to get SESSION OUT when the session times out:

    public void sessionCreated(HttpSessionEvent arg0) {  
        System.out.print("SESSION Created");
    }

    public void sessionDestroyed(HttpSessionEvent arg0) {
        System.out.print("SESSION OUT");
    }

and I set in web.xml:

  <session-config>
     <session-timeout>1</session-timeout> 
  </session-config>

The servlet waits more than two minutes, then it calls sessionDestroyed.

Is there is a way to force sessionDestroyed when time out ?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What makes you think that sessionDestroyed is not being called when the session times out? Or in other words, what's you interpretation of the fact it gets called at all?

The servlet will handle the validity of sessions in its own manner, including session timeouts, and when it determines that the session is no longer valid it will call your method. However, I don't think any servlets guarantee any particular timeliness in this regard; my understanding is that it's a bit like garbage collection in that it is guaranteed to happen at some point, but not necessarily at the earliest possible instance that the session becomes eligible for destruction.

In any case, it seems almost certain that the servlet is doing what you want - seeing that the session is timed out and calling the appropriate method - the only question is whether you're going to see this exactly 60 seconds after the last request or a bit later. I would suggest that in general you shouldn't rely on the exact timings of when this method is called; use it to clear up resources, sure, but not for something like program correctness (you'll get IllegalStateExceptions if calling methods on an invalid session anyway). If you feel you really must rely on this, perhaps explain what you're doing so that others can suggest more suitable ways to achieve this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...