2021-12-08 web监听器

2021-12-08 web监听器

2021-12-08 web监听器

在web.xml 的Listener中注册
filter也是在web.xml 中注册的

web监听器定义:是一个Servlet的特殊类,在web.xml 文件中定义

作用:
1- 监听request对象、session对象、context对象的创建和销毁,并在创建和销毁的时候附加额外操作【如设置全局变量,获取session信息
2- 监听以上三个对象的attribute属性信息的增加和删除的时候的事件,做额外操作。

  1. web 监听器监听对象
    1)Servlet Context
    2)Session
    3)Servlet Request

  2. web 监听器用途(使用场景)
    1)统计在线人数
    2)系统启动时加载初始化信息
    3)统计网站访问量
    4)Spring

  3. 使用方法
    如:
    1)实现ServletContxtListener 接口
    【context对象是上下文对象,在应用启动时初始化,应用停止时销毁】
    重写有两个方法(即context的初始化和销毁方法):
    1> contextInitialized()
    2> contextDestroyed()
    2)在web.xml 中注册!!!

  4. 监听器的启动顺序
    优先级:监听器 > 过滤器 > servlet

  5. 监听器的分类
    1)ServletContext
    ServletContextListener()
    用于监听应用程序环境对象的事件监听器
    用作:定时器;全局属性参数(Context Attribute【set get】)
    web.xml中可以定义Servlet Context参数,在实现ServletContxtListener实现类的init方法中获取参数;
    也可以在init方法中setAttribute()
    2)HttpSession
    HttpSessionListener()
    Session对象有过期时间,可以在session中存一些用户的信息
    监听用户会话对象的事件监听器
    用于在线用户统计、访问量统计
    3)ServletRequest
    监听请求消息对象的事件监听器
    ServletRequest对象也就是URL访问的时候,里边的参数
    1)path Variable
    2)https://www.baidu.com/s?wd=gitee 其中wd就是参数名

  6. 属性的增加和删除的 事件监听器
    1)ServletContextAttributeListener

  1. HttpSessionAttributeListener
  2. ServletRequestAttributeListener

使用方式:
比如在JSP页面中:

request.setAttribute("requestName", "requestValue");
request.getSession().setAttribute("sessionName", "sessionValue");
request.getSession().getServletContext().setAttribute("contextAttrName", "contextAttrValue");

使用以上的方法时,在后台实现上边的三个Listener的方法,就会监听到attribute的变化。

  • request.getContextPath() 就是项目设置的如: /api/…的接口路径

    1. @WebListener(valueName = “ListenerName”)
      在ServletContextListener或者HttpSessionListener的实现类上使用@WebListener,就可以实现监听器的声明。
      ==》所以不需要在web.xml中注册标签class.listenerName
      ==》直接用注解即可!!!
    1. 案例:统计系统在线用户数
      实现步骤:
      1)确定使用HttpSessionListener监听器、以及ServletRequestListener监听器
      2)还要用ServletContext.setAttribute(“userList”, userList) 来全局维护一个userList对象
      3)新增用户数:
      当有request请求到服务器的时候:

ServeletRequestListener监听器获取到

	List<User> list = HttpRequest.getSession().getAttribute("userList")

2 判断当前访问的用户是否在list中,没有则add到list中。

HttpSessionListenersessionCreated(HttpSessionEvent arg0){
		userNum++;
		arg0.getSession().getServletContext().setAttribute(userNum);
	}

3)删除用户数:
当用户离开系统的时候:

	HttpSessionListenersessionDestroyed(HttpSessionEvent arg0){
		userNum--;
		arg0.getSession().getServletContext().setAttribute(userNum);
		user = SessionUtil.getUserBySessionId(arg0.getSessionId());
		session.getAttr("userList").remove(user);
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值