session的創建
一般認爲session的創建是在打開瀏覽器輸入地址,回車的時候就創建了session。經過測試,其實不然。
session的創建需要在服務端調用了HttpServletRequest.getSession()方法時,纔會被創建。而getSession方法有兩個
HttpSession |
getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. |
HttpSession |
getSession(boolean create) Returns the current HttpSession associated with this request or, if there is no current session and create is
true, returns a new session. |
如果設置了session的創建和銷燬方法,即會調用HttpSessionListener的sessionCreated和sessionDestroyed方法,參見session的監控
一般頁面的session時間設置有三種方法
具體設置很簡單,方法有三種:
(1)在主頁面或者公共頁面中加入:session.setMaxInactiveInterval(900);
參數900單位是秒,即在沒有活動15分鐘後,session將失效。設置爲-1將永不關閉。
這裏要注意這個session設置的時間是根據服務器來計算的,而不是客戶端。
(2)也是比較通用的設置session失效時間的方法,就是在項目的web.xml中設置
<session-config>
<session-timeout>15</session-timeout>
</session-config>
這裏的15也就是15分鐘失效.
(3)直接在應用服務器中設置,如果是tomcat,可以在tomcat目錄下conf/web.xml中
找到<session-config>元素,tomcat默認設置是30分鐘,只要修改這個值就可以了。
需要注意的是如果上述三個地方如果都設置了,有個優先級的問題,從高到低:
(1)>(2)>(3)
session的監聽
繼承HttpSessionListener類,有sessionCreated和sessionDestroyed兩個方法
package com.sygroup.util;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionMonitor implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent event) {
// TODO Auto-generated method stub
logger.info("session created==============");
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
// TODO Auto-generated method stub
logger.info("session destroy==============:"+(currentUser==null?"":currentUser.getUserName()));
}
}
然後在web.xml中聲明
<listener>
<listener-class>
com.sygroup.util.SessionMonitor
</listener-class>
</listener>