Listener简要说明
1.实现一个监听器的接口(有N种)具体看继承哪个监听器接口
实例一:监听session个数确定网站访问人数
//监听器配置
public class OnlineCountListener implements HttpSessionListener {
//session创建监听
//一旦创建一个session就会触发这个事件
public void sessionCreated(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
Integer count = (Integer)context.getAttribute("OnlineCount");
if (count == null) {
count = 1;
}else{
count++;
}
context.setAttribute("OnlineCount",count);
}
//session销毁监听
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext context = se.getSession().getServletContext();
Integer count = (Integer)context.getAttribute("OnlineCount");
if (count == null) {
count = 0;
}else{
count--;
}
context.setAttribute("OnlineCount",count);
}
}
xml配置
<!--注册监听器-->
<listener>
<listener-class>com.zhang.listener.OnlineCountListener</listener-class>
</listener>
网站初始化页面定义显示
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>当前有<span><%=request.getServletContext().getAttribute("OnlineCount")%></span>人在线</h1>
</body>
</html>
显示结果两个浏览器进程访问
本文来自博客园,作者:Cn_FallTime,转载请注明原文链接:https://www.cnblogs.com/CnFallTime/p/15978715.html