根據書本寫了下面這個監聽器,然后開始調試,打開一個瀏覽器來訪問該網頁,可以正常觸發sessionCreated,然后關閉瀏覽器,發現沒有觸發sessionDestroyed,然后我懷疑是不是這個監聽器的機制有問題,等了好幾分鍾都沒有反應。
@WebListener
public class OnlineUserCounter implements HttpSessionListener {
private static int counter;
public static int getCounter()
{
return counter;
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
OnlineUserCounter.counter++;
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
OnlineUserCounter.counter--;
}
}
后來想起在樹上看到說session是有一個超時時間的,瀏覽器關閉其實對於web服務器來說是不知道的,所以他需要等待超時時間到了之后自動銷毀,上面關閉瀏覽器之后只所以沒有促發sessionDesroyed,就是因為默認的超時時間沒到。
默認超時時間太長了,所以在sessionCreated中添加如下代碼,改小超時時間:
arg0
.getSession().setMaxInactiveInterval(5);
這樣只要用瀏覽器訪問該站點,然后5s不刷新之后,sessionDestroyed就會被自動調用了。