监听器 在线人数统计

2018-12-26

package com.fz.servlet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class Observers implements HttpSessionListener, HttpSessionAttributeListener{

	//在线总人数
	public static int count;
	//会员在线人数
	public static List<String> vipnums = new ArrayList<>();
	@Override
	public void sessionCreated(HttpSessionEvent e) {
		count++;
		System.out.println("有人上线");
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent e) {
		count--;
		System.out.println("有人下线");
		
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent e) {
		// session.setAttribute() 执行时
		HttpSession session = e.getSession();
		System.out.println(session);//session地址
		System.out.println(session.getId());//session id
		System.out.println(e.getName());//session名
		System.out.println(e.getValue());//session值
		System.out.println(session.getAttribute(e.getName()));//session值
		
		String nameString = (String) e.getValue();
		vipnums.add(nameString);
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent e) {
		// session.removeAttribute() 执行时
		vipnums.remove(e.getValue().toString());
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent e) {
		// session.setAttribute()
		// session.setAttribute();第二次执行时(重新登录时执行)
	}

}

下载地址

百度网盘
密码: