Loading

Java之Listener

Java之Listener

Listener监听器

监听器有很多种,大部分还是在GUI用的比较多,这里简单记录一点关于HttpSessionListener的

统计session count Listener。主要通过ServletContext上下文来存储session count,在listener中create和destroyed方法实现session count的逻辑,主要是将ServletContext作为第三方来进行session count值的存储与改动。通过jsp中application对象get上下文属性来获取count值实现实时显示session的数量。

public class OnlineCountListener implements HttpSessionListener {

    //创建session监听
    //一旦创建session就会触发该事件
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println(httpSessionEvent.getSession().getId());
        //每次有session创建,代表用户数量+1
        HttpSession session = httpSessionEvent.getSession();

        //获取上下文,将人数OnlineCount存入上下文中方便读写
        ServletContext sct = session.getServletContext();

        Integer OnlineCount = (Integer) sct.getAttribute("OnlineCount");

        if (OnlineCount==null){
            OnlineCount = new Integer(1);
        }else {
            int count = OnlineCount.intValue();
            OnlineCount = new Integer(count+1);
        }
        //数值通过属性存入上下文中
        sct.setAttribute("OnlineCount", OnlineCount);
    }

    //销毁session监听
    //一旦销毁session就会触发该事件
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
//每次有session创建,代表用户数量+1
        HttpSession session = httpSessionEvent.getSession();

        //获取上下文,将人数OnlineCount存入上下文中方便读写
        ServletContext sct = session.getServletContext();

        Integer OnlineCount = (Integer) sct.getAttribute("OnlineCount");

        if (OnlineCount==null){
            OnlineCount = new Integer(0);
        }else {
            int count = OnlineCount.intValue();
            OnlineCount = new Integer(count-1);
        }
        //数值通过属性存入上下文中
        sct.setAttribute("OnlineCount", OnlineCount);
    }
}

web.xml配置Listener

<listener>
    <listener-class>com.zh1z3ven.listener.OnlineCountListener</listener-class>
</listener>

Index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>OnlineCount</title>
</head>
<body>
<h2 align="center">当前在线人数为:<span><%= application.getAttribute("OnlineCount")%></span></h2>
</body>
</html>

posted @ 2021-08-05 00:26  Zh1z3ven  阅读(300)  评论(0编辑  收藏  举报