1.监听器定义
监听器也叫Listener,是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。
2.常见的监听器
1)ServletContextAttributeListener
ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改属性。
ServletContextListener监听ServletContext对象。
当创建ServletContext时,激发contextInitialized(ServletContextEvent sce)方法;
当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。
2)HttpSessionListener
HttpSessionListener监听HttpSession的操作:
当创建一个Session时,激发sessionCreated(HttpSessionEvent se)方法;
当销毁一个Session时,激发sessionDestroyed(HttpSessionEvent se)方法。
3)HttpSessionAttributeListener
HttpSessionAttributeListener监听HttpSession中的属性的操作:
当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se)方法;
当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;
当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。
3.案例 监听器统计在线人数
用户登录成功后将登录信息存储至session中 然后在监听器内进行计算 显示数量在页面
shouye.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: root
Date: 2021/9/24
Time: 11:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
欢迎:${student.name},当前在线人数:${count}
</table>
</body>
</html>
listener.OnlineListener.java
package listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class OnlineListener implements HttpSessionAttributeListener {
private static int count=0;
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
System.out.println("添加session属性值");
Object user=se.getSession().getAttribute("student");
if(user!=null){
count++;
se.getSession().getServletContext().setAttribute("count",count);
}
}
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
System.out.println("移除session属性...");
count--;
se.getSession().getServletContext().setAttribute("count",count);
}
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
}
}