Listener监听在线用户数量

一、在web.xml中注册监听类

	<listener>
		<listener-class>
			com.sasis.webapp.listener.OnLineUserListener
		</listener-class>
	</listener>

二、OnLineUserListener.java操作在线人数,实时更新数据库
package com.sasis.webapp.listener;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sasis.model.UserLoginLog;
import com.sasis.service.UserLoginLogManager;

public class OnLineUserListener implements HttpSessionListener {
	public OnLineUserListener() {
	}

	private static Map onlineUsers = Collections.synchronizedMap(new HashMap(100));



	public static int getCount() {
		return onlineUsers.size();
	}


	public static Collection getOnlineUsers() {
		return onlineUsers.values();
	}
	

	public static boolean isUserOnline(UserLoginLog userLoginLog) {
		if (onlineUsers.containsKey(userLoginLog.getUserName())) {
			return true;
		}
		return false;
	}


	public void deleteUser(UserLoginLog userLoginLog) {
		onlineUsers.remove(userLoginLog.getUserName());
	}


	public static void addUser(UserLoginLog userLoginLog) {
		onlineUsers.put(userLoginLog.getUserName(), userLoginLog);
	}

	public void sessionCreated(HttpSessionEvent hse) {

	}
	/**
	sessionDestroyed()方法在两种情况下调用
	1、web.xml中配置的过期时间,单位为min。过期调用
	<session-config>
		<session-timeout>200</session-timeout>
	</session-config>
	2、调用session.invalidate()触发
	**/
	public void sessionDestroyed(HttpSessionEvent hse) {
		HttpSession session = hse.getSession();
		UserLoginLog userLoginLog = (UserLoginLog) session.getAttribute("userLoginLog");
		if (userLoginLog != null) {
			deleteUser(userLoginLog);//在线用户集合中移除该用户
			ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext());
			userLoginLog.setLoginOutTime(new Timestamp(new Date().getTime()));
			UserLoginLogManager ullmgr = (UserLoginLogManager) ctx.getBean("userLoginLogManager");
			ullmgr.updateUserLoginLog(userLoginLog);//实时的更新数据库用户登录状态
		}
	}

}
、通过实现
通过实现HttpSessionListener的sessionCreated()方法可监听用户登录,将用户添加入在线用户集合

四、可用以下界面对在线用户进行展现

Listener监听在线用户数量_第1张图片


Listener监听在线用户数量_第2张图片

你可能感兴趣的:(listener)