统计在线人数–监听器
@WebListener()
public class MyListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
HttpSession httpSession = httpSessionBindingEvent.getSession();
ServletContext servletContext = httpSession.getServletContext();
int count = (int)servletContext.getAttribute("count");
servletContext.setAttribute("count",count+1);
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
HttpSession httpSession = httpSessionBindingEvent.getSession();
ServletContext servletContext = httpSession.getServletContext();
int count = (int)servletContext.getAttribute("count");
servletContext.setAttribute("count",count-1);
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("servletContext初始化");
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("count",0);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession httpSession = httpSessionEvent.getSession();
Object username = httpSession.getAttribute("username");
Object password = httpSession.getAttribute("password");
Object id = httpSession.getAttribute("id");
if (username!=null && password!=null && id != null){
httpSession.removeAttribute("username");
httpSession.removeAttribute("password");
httpSession.removeAttribute("id");
}
}
}