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属性信息的增加和删除的时候的事件,做额外操作。
-
web 监听器监听对象
1)Servlet Context
2)Session
3)Servlet Request -
web 监听器用途(使用场景)
1)统计在线人数
2)系统启动时加载初始化信息
3)统计网站访问量
4)Spring -
使用方法
如:
1)实现ServletContxtListener 接口
【context对象是上下文对象,在应用启动时初始化,应用停止时销毁】
重写有两个方法(即context的初始化和销毁方法):
1> contextInitialized()
2> contextDestroyed()
2)在web.xml 中注册!!! -
监听器的启动顺序
优先级:监听器 > 过滤器 > servlet -
监听器的分类
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就是参数名 -
属性的增加和删除的 事件监听器
1)ServletContextAttributeListener
- HttpSessionAttributeListener
- ServletRequestAttributeListener
使用方式:
比如在JSP页面中:
request.setAttribute("requestName", "requestValue");
request.getSession().setAttribute("sessionName", "sessionValue");
request.getSession().getServletContext().setAttribute("contextAttrName", "contextAttrValue");
使用以上的方法时,在后台实现上边的三个Listener的方法,就会监听到attribute的变化。
-
request.getContextPath() 就是项目设置的如: /api/…的接口路径
-
- @WebListener(valueName = “ListenerName”)
在ServletContextListener或者HttpSessionListener的实现类上使用@WebListener,就可以实现监听器的声明。
==》所以不需要在web.xml中注册标签class.listenerName
==》直接用注解即可!!!
- @WebListener(valueName = “ListenerName”)
-
- 案例:统计系统在线用户数
实现步骤:
1)确定使用HttpSessionListener监听器、以及ServletRequestListener监听器
2)还要用ServletContext.setAttribute(“userList”, userList) 来全局维护一个userList对象
3)新增用户数:
当有request请求到服务器的时候:
- 案例:统计系统在线用户数
ServeletRequestListener监听器获取到
List<User> list = HttpRequest.getSession().getAttribute("userList");
2 判断当前访问的用户是否在list中,没有则add到list中。
HttpSessionListener的sessionCreated(HttpSessionEvent arg0){
userNum++;
arg0.getSession().getServletContext().setAttribute(userNum);
}
3)删除用户数:
当用户离开系统的时候:
HttpSessionListener的sessionDestroyed(HttpSessionEvent arg0){
userNum--;
arg0.getSession().getServletContext().setAttribute(userNum);
user = SessionUtil.getUserBySessionId(arg0.getSessionId());
session.getAttr("userList").remove(user);
}