1. 程式人生 > 實用技巧 >HttpSessionListener介面監聽網站線上人數

HttpSessionListener介面監聽網站線上人數

>>> hot3.png

listener程式碼

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 packagecom.chinaseacom.store.common; importjavax.servlet.http.HttpSessionEvent; importjavax.servlet.http.HttpSessionListener; publicclassMySessionListenerimplementsHttpSessionListener{ privatelongonlineCount; publicvoidsessionCreated(HttpSessionEventevent){ this.onlineCount=this.onlineCount+1; //儲存在application作用域 event.getSession().getServletContext().setAttribute("onlineCount",onlineCount); } publicvoidsessionDestroyed(HttpSessionEventevent){ this.onlineCount=this.onlineCount-1; event.getSession().getServletContext().setAttribute("onlineCount",onlineCount); } }

web.xml中配置

1 2 3 4 <!--配置自定義監聽器--> <listener> <listener-class>com.chinaseacom.store.common.MySessionListener</listener-class> </listener>

jsp頁面

1 ${application.onlineCount}


要了解Session首先要知道一個概念:Session的銷燬只有兩種情況:

第一:session呼叫了 session.invalidate()方法.

第二:前後兩次請求超出了session指定的生命週期時間. 其中Session的生命週期時間可以在web.xml配置. 預設30分鐘

在web.xml可以做如下配置:

1 2 3 <session-config> <session-timeout>5</session-timeout> </session-config>


Tomcat 預設是會在一個 application 停止的時候,將其所有的session都序列化Tomcat安裝目錄\work\Catalina\localhost\專案名 資料夾下面看到有一個 SESSIONS.ser 的檔案中,然後在下次啟動的時候,在反序列化,繼續尚未過期的session的。


tomcat單獨停止某個應用需要到tomcat管理介面


wKioL1XIngqzJBjzAAWHD9Ijw5Y729.jpg

禁用tomcat session序列化

在tomcat配置檔案server.xml中context節點配置saveOnRestart="false"

1 2 3 4 5 6 7 8 9 10 11 <HostappBase="webapps"autoDeploy="true"name="localhost"unpackWARs="true"> <ValveclassName="org.apache.catalina.valves.AccessLogValve"directory="logs"pattern="%h%l%u%t&quot;%r&quot;%s%b"prefix="localhost_access_log."suffix=".txt"/> <ContextdocBase="admin"path="/admin"reloadable="true"source="org.eclipse.jst.jee.server:admin"> <ManagerclassName="org.apache.catalina.session.PersistentManager"saveOnRestart="false"> <StoreclassName="org.apache.catalina.session.FileStore"/> </Manager> </Context> </Host>


path:指定訪問該Web應用的URL入口。


docBase:指定Web應用的檔案路徑,可以給定絕對路徑,也可以給定相對於的appBase屬性的相對路徑,如果Web應用採用開放目錄結構,則指定Web應用的根目錄,如果Web應用是個war檔案,則指定war檔案的路徑。(指定專案所在地址)


reloadable:如果這個屬性設為true,tomcat伺服器在執行狀態下會監視在WEB-INF/classes和WEB-INF/lib目錄下class檔案的改動,如果監測到有class檔案被更新的,伺服器會自動重新載入Web應用。

轉載於:https://my.oschina.net/liting/blog/535275