Listener监听器
实现监听器的接口
平时几乎用不到监听器,更多的是在 GUI编程
中用到
判断实际情况是否需要使用监听器
代码示例
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数:统计session的数量
//Listener的种类非常多!!!如果都学了的话,就不用干别的了
public class OnlineCountListener implements HttpSessionListener {
//创建Session的监听:看你的一举一动
//每创建一个session,就会触发一次这个事件
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer)ctx.getAttribute("OnlineCount");
System.out.println(se.getSession().getId());
//项目刚启动的时候,会看到有3人 同时在线,因为Tomcat在启动服务的时候,会做一些事情,在这个过程中启用了几个session
//当我们Redeploy重新发布项目的时候,他就会恢复正常了
if (onlineCount == null){
onlineCount = 1;
}else{
int count = onlineCount;
onlineCount = count + 1;
}
ctx.setAttribute("OnlineCount",onlineCount);
}
//销毁Session的监听
//每销毁一个session,就会触发一次这个事件
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer)ctx.getAttribute("OnlineCount");
if (onlineCount == null){
onlineCount = 0;
}else{
int count = onlineCount;
onlineCount = count - 1;
}
ctx.setAttribute("OnlineCount",onlineCount);
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>当前有 <span><%= this.getServletConfig().getServletContext().getAttribute("OnlineCount")%></span> 人</h1>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!--注册监听器-->
<!--只要把他配置在这里,他自己就会生效了-->
<listener>
<listener-class>com.mahe666.listener.OnlineCountListener</listener-class>
</listener>
</web-app>