监听器(Listener)

 1. 概念

      监听对象的创建和销毁

      监听对象的属性操作。(增加、修改、删除)

 2. 分类

      监听域对象的创建和销毁

        ServletRequestListener

        HttpSessionListener

        ServletContextListener

      监听对象的属性操作

        ServletRequestAttributeListener

        HttpSessionAttributeListener

        ServletContextAttributeListener

 3. 典型应用

      统计在线人数

 4. 统计在线人数实现步骤

      1. 创建一个Listener监听器的类,监听session创建和销毁。实现HttpSessionListener

/**
 * 监听session的创建
 */
@WebListener
public class OnlineNumListener implements HttpSessionListener{

    public OnlineNumListener() {
    }
    /**
     * 监听session对象创建调用,在线人数+1
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext application=se.getSession().getServletContext();
        if(application.getAttribute("count")!=null){
            int count =(int)application.getAttribute("count");
            application.setAttribute("count",count+1);
        }else{
            application.setAttribute("count",1);
        }
    }
    /**
     * 监听session销毁调用,在线人数-1
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext application=se.getSession().getServletContext();
        int count =(int)application.getAttribute("count");
        application.setAttribute("count",count-1);
    }
}

   2. 编写jsp页面展示在线人数

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <body>
     <h2>在线人数:${count}</h2>
     <a href="exitServlet">退出</a>
  </body>
</html>

  3. 退出

@WebServlet(name = "ExitServlet", value = "/exitServlet")
public class ExitServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();
        //销毁session
        session.invalidate();
    }
}

解决控制台乱码问题

IDEA 控制台中文乱码4种解决方案_java_脚本之家

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值