日期:2014-05-19  浏览次数:20687 次

Tomcat session数量能统计吗?
如题

------解决方案--------------------
个人认为可以:在application中定义一个数量,利用HttpSessionListener在session创建时+1,session销毁时-1.
------解决方案--------------------
Java code

package web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class CountListener implements HttpSessionListener {
 private int count=0;
    public void sessionCreated(HttpSessionEvent arg0) {
        System.out.println("sessionCreated");
        count++;
        HttpSession session=arg0.getSession();
        ServletContext sctx=session.getServletContext();
        sctx.setAttribute("count", count);
        
        
    }

    public void sessionDestroyed(HttpSessionEvent arg0) {
        System.out.println("sessionDestroyed");
        count--;
        HttpSession session=arg0.getSession();
        ServletContext sctx=session.getServletContext();
        sctx.setAttribute("count", count);        
    }

}

------解决方案--------------------
Java code

package com.test;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
class SessionCountListener implements HttpSessionListener{
 public static long sessionCount=0;
  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
    sessionCount++; 
  }

  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
    // TODO Auto-generated method stub
    
  }  
}