package com.tfy.heima.listener;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import com.tfy.heima.domain.User;
public class OnlineUserListener implements HttpSessionAttributeListener {
//Map<String,HttpSession>
public void attributeAdded(HttpSessionBindingEvent se) {
HttpSession session=se.getSession();
Object obj=session.getAttribute("user");
if(obj!=null && obj instanceof User){
User user=(User)obj;
ServletContext sc=session.getServletContext();
Map<String, HttpSession> map=(Map<String, HttpSession>) sc.getAttribute("users");//保存所有登录有关的map对象
if(map==null){
map=Collections.synchronizedMap(new HashMap<String, HttpSession>());
sc.setAttribute("users", map);
}
map.put(user.getUsername(), session);
}
}
public void attributeRemoved(HttpSessionBindingEvent se) {
}
public void attributeReplaced(HttpSessionBindingEvent se) {
}
}
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import com.tfy.heima.domain.User;
public class OnlineUserListener implements HttpSessionAttributeListener {
//Map<String,HttpSession>
public void attributeAdded(HttpSessionBindingEvent se) {
HttpSession session=se.getSession();
Object obj=session.getAttribute("user");
if(obj!=null && obj instanceof User){
User user=(User)obj;
ServletContext sc=session.getServletContext();
Map<String, HttpSession> map=(Map<String, HttpSession>) sc.getAttribute("users");//保存所有登录有关的map对象
if(map==null){
map=Collections.synchronizedMap(new HashMap<String, HttpSession>());
sc.setAttribute("users", map);
}
map.put(user.getUsername(), session);
}
}
public void attributeRemoved(HttpSessionBindingEvent se) {
}
public void attributeReplaced(HttpSessionBindingEvent se) {
}
}