(web后端)07_监听器Listener

本文介绍了Web后端的监听器(Listener)概念,它用于监视对象的特定行为并作出响应。详细讲解了Servlet监听器如ServletContextListener、HttpSessionListener等的使用,并通过创建步骤展示了如何在实际应用中实现监听器。此外,还提到了监听器在统计在线人数方面的典型应用,以及监听器的生命周期、属性操作和实现与配置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Listener:监听器

监视某一对象,当该对象发生某些特定的行为时 对其采取响应的措施。
事件监听机制

		* 事件	:一件事情
		* 事件源 :事件发生的地方
		* 监听器 :一个对象
		* 注册监听:将事件、事件源、监听器绑定在一起。 当事件源上发生某个事件后,执行监听器代码

WEB中的监听器:

监听对象:ServletContext  HttpSession  HttpServletRequest
包括监听对象本身 还包括监听对象的属性的变化

提供的监听器:

1 ServletContext 对象:ServletContextListener  SerlvetContextAttributeListener
2 HttpSession对象 :HttpSessionListener  HttpSessionAttributeListener
3 HttpServletRequest对象 ServletRequestListener  ServletRequestAttributListener

ServletContextListener
在这里插入图片描述
SerlvetContextAttributeListener
在这里插入图片描述
HttpSessionListener
在这里插入图片描述
HttpSessionAttributeListener
在这里插入图片描述ServletRequestListener
在这里插入图片描述
ServletRequestAttributListener
在这里插入图片描述

二、Listener监听器的基本使用

创建步骤:

1、创建一个实现监听器接口的类
2、配置web.xml文件,注册监听器

RequestServlet

@WebServlet("/req.do")
public class RequetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("_method");
        switch (method){
            case "add":
                addAttr(req,resp);
                break;
            case "remove":
                removeAttr(req,resp);
                break;
            case "replace":
                replaceAttr(req,resp);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    public void addAttr(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("username","admin");
    }
    public void removeAttr(HttpServletRequest req, HttpServletResponse resp){
        req.removeAttribute("username");
    }
    public void replaceAttr(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("username","tom");
    }
}

RequestAttributeListener

public class RequestAttributeListener implements ServletRequestAttributeListener {
    @Override
    public void attributeAdded(ServletRequestAttributeEvent srae) {
        System.out.println("新增了一个属性"+srae.getName()+"----"+srae.getValue());
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
        System.out.println("移除了一个属性"+srae.getName()+"----"+srae.getValue());
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
        System.out.println("替换了一个属性"+srae.getName()+"----"+srae.getValue());
    }
}

RequsetListener

public class RequsetListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("请求销毁...");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("请求创建....");
    }
}

web.xml

<!-- 配置监听器 完成监听器的注册-->
    <listener>
        <listener-class>org.lanqiao.web.listener.RequsetListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.lanqiao.web.listener.RequestAttributeListener</listener-class>
    </listener>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="/req.do?_method=add">新增一个属性</a>
    <a href="/req.do?_method=remove">删除一个属性</a>
    <a href="/req.do?_method=replace">替换一个属性</a>
  </body>
</html>

三、监听器的典型应用:

需求:监听当前在线人数。
监听对象Session,在线人数列表是对所有人起作用,数据应放到application中。即ServletContext对象
logout

@WebServlet("/logout.do")
public class logout extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

OnlineUserListen

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

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer onLineCount = (Integer) context.getAttribute("onLineCount");
        if (onLineCount == null){
            onLineCount = 1;
        }else {
            onLineCount--;
        }
        context.setAttribute("onLineCount",onLineCount);
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <h1>当前在线人数为:${onLineCount}</h1>
    <a href="/logout.do">安全退出</a>
  </body>
</html>

在这里插入图片描述

总结:

监听器:

SerlvetContext
HttpSession
ServletRequest

生命周期:创建 销毁
属性:添加 修改 移除
实现方式:实现对应的接口 重写接口
配置:xml配置 注解配置
xml:注册监听器 注解:@Weblistener

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值