监听器

统计在线人数

@WebListener
public class CountOnlineListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        Integer countOnline = (Integer) se.getSession().getServletContext().getAttribute("CountOnline");
        if (countOnline == null) {
            se.getSession().getServletContext().setAttribute("CountOnline", 1);
        } else {
            se.getSession().getServletContext().setAttribute("CountOnline", countOnline + 1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        Integer countOnline = (Integer) se.getSession().getServletContext().getAttribute("CountOnline");
        System.out.println(countOnline);
        se.getSession().getServletContext().setAttribute("CountOnline", countOnline - 1);
        countOnline = (Integer) se.getSession().getServletContext().getAttribute("CountOnline");
        System.out.println(countOnline);
    }
}

posted @ 2021-01-16 22:47  神乐g  阅读(59)  评论(0编辑  收藏  举报