Listener 快速开始

时间:2023-03-09 03:42:11
Listener 快速开始

【SessionListener】

@WebListener
public class SessionListener implements HttpSessionListener,HttpSessionIdListener{
@Override
public void sessionIdChanged(HttpSessionEvent e, String oldSessionId) {
SessionRegistry.updateSessionId(e.getSession(),oldSessionId);
System.out.println(this.date()+":Session ID:"+oldSessionId+" changed to "+e.getSession().getId());
} private String date() {
SimpleDateFormat f = new SimpleDateFormat("EEE dd,mm,yyyy HH:mm:ss");
return f.format(System.currentTimeMillis());
} @Override
public void sessionCreated(HttpSessionEvent e) {
SessionRegistry.addSession(e.getSession());
System.out.println(this.date() + ":Session "+e.getSession().getId()+"created.");
} @Override
public void sessionDestroyed(HttpSessionEvent e) {
SessionRegistry.removeSession(e.getSession());
System.out.println(this.date() + ":Session "+e.getSession().getId()+"destroyed.");
}
}

【SessionRegistry】比较轻量,私有构造,一些静态方法

public final class SessionRegistry {
private static final Map<String,HttpSession> SESSIONS = new Hashtable<>();
public static void addSession(HttpSession session){
SESSIONS.put(session.getId(),session);
}
public static void updateSessionId(HttpSession session,String oldSessionId){
synchronized (SESSIONS){
SESSIONS.remove(oldSessionId);
addSession(session);
}
} public static void removeSession(HttpSession session){
SESSIONS.remove(session.getId());
} public static List<HttpSession> getAllSessions(){
return new ArrayList<>(SESSIONS.values());
} public static int getNumberOfSessions(){
return SESSIONS.size();
}
private SessionRegistry(){}
} 【web.xml】
<listener>
<listener-class>net.mypla.SessionListener</listener-class>
</listener>