算了,好人做到底,程序也给你吧
package com.test;
import javax.servlet.http.*;
import java.util.*;
public class SessionListener implements HttpSessionListener,HttpSessionAttributeListener{
private static HashMap hUserName = new HashMap();//保存sessionID和username的映射
/**以下是实现HttpSessionListener中的方法**/
/*创建session时,什么都不做*/
public void sessionCreated(HttpSessionEvent se){
}
/*session失效时,删除列表中用户信息*/
public void sessionDestroyed(HttpSessionEvent se){
hUserName.remove( se.getSession().getId() );
}
/**以下是实现HttpSessionAttributeListener中的方法**/
/*调用session.setAttribute( "username ", "**** ")时,添加用户信息到列表中*/
public void attributeAdded(HttpSessionBindingEvent se){
if(se.getName().equals( "username ")){
hUserName.put(se.getSession().getId(),se.getValue());
}
}
/*调用session.removeAttribute( "username ", "**** ")时,删除列表中用户信息*/
public void attributeRemoved(HttpSessionBindingEvent se){
if(se.getName().equals( "username ")){
if(hUserName.containsValue(se.getValue())){
Iterator iter = hUserName.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
if( ( (String)val ).equals(se.getValue()) ){
hUserName.remove(key);
}
}
}
}
}
/*调用更改 "username "属性值时同时更改列表中用户信息*/
public void attributeReplaced(HttpSessionBindingEvent se){
if(se.getName().equals( "username ")){
if(hUserName.containsValue(se.getValue())){
Iterator iter = hUserName.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
if( ( (String)val ).equals(se.getValue()) ){
hUserName.remove(key);
hUserName.put(key,se.getValue());
}
}
}
}
}
/*返回用户列表*/
public static HashMap getList(){
return hUserName;
}
}
在WEB-INF下面的web.xml中配置监听
<listener>
<listener-class> com.test.SessionListener </listener-class>
</listener>