1. 程式人生 > >Session監聽統計網站的線上人數HashSet

Session監聽統計網站的線上人數HashSet

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

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

public class OaSessionListener implements HttpSessionListener {
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		HttpSession session = arg0.getSession();
		ServletContext application = session.getServletContext();
		// 在application範圍有一個HshSet集儲存所有的Session
		 HashSet sessions= (HashSet) application.getAttribute("sessions");
		 if(sessions == null){ 
			sessions=new HashSet();
		 	application.setAttribute("sessions", sessions); 
		 }
		 //新建立的session均新增到HashSet集中 
		 sessions.add(session);
		 System.out.println("當前線上人數:" + sessions.size() + "人");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		HttpSession session = arg0.getSession();
		ServletContext application = session.getServletContext();
		HashSet sessions=(HashSet) application.getAttribute("sessions");
		//銷燬的session均從HshSet中移除 
		sessions.remove(sessions);
		System.out.println(sessions.size());
		 

	}

}