HttpSessionListener接口监听网站在线人数

listener代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.chinaseacom.store.common;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {  
      
    private long onlineCount;  
  
    public void sessionCreated(HttpSessionEvent event) {  
       
       this.onlineCount=this.onlineCount+1;  
                                //保存在application作用域  
        event.getSession().getServletContext().setAttribute("onlineCount", onlineCount);  
    }  
   
    public void sessionDestroyed(HttpSessionEvent event) {  
         
        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管理界面


HttpSessionListener接口监听网站在线人数

禁用tomcat session序列化

在tomcat配置文件server.xml中context节点配置saveOnRestart="false"

1
2
3
4
5
6
7
8
9
10
11
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
        
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>
 
<Context docBase="admin" path="/admin" reloadable="true" source="org.eclipse.jst.jee.server:admin">       
<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="false">
<Store className="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