在线人数统计
涉及的技术知识点
监听器
监听器
-
Listener用于监听JavaWeb程序中的事件。
-
例如:ServletContext、HttpSession、ServletRequest的创建、修改和删除。
-
监听器的类型分为
- 生命周期
- 数据绑定
创建listener
@WebListener()
public class LoginListener implements HttpSessionListener {
// -------------------------------------------------------
// HttpSessionListener implementation
// -------------------------------------------------------
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
//ServletContext :Servlet上下文对象.
// WEB应用服务器会为每个web应用创建唯一一个ServletContext对象.
// 在整个web应用中作用域最大且是所有的用户可共享的.
// ServletContext在web引用服务器启动则被创建, 服务器销毁此对象才会被销毁.
//获取到ServletContext
ServletContext sc = se.getSession().getServletContext();
//我们会在ServletContext中绑定一个在线人数, 通过 count 这个key
//尝试从Servletcontext中获取 count
Object count = sc.getAttribute("count");
if(count == null){
sc.setAttribute("count",1);
}else {
sc.setAttribute("count",(Integer)count + 1);
}
}
public void sessionDestroyed(HttpSessionEvent se) {
}
main.jsp
代码:
<body>
<h1 align="center">欢迎<font color="red">${sessionScope.loginUser.username}</font>登录</h1>
<br>
<h2 align="center">当前在线人数:<font color="red">${applicationScope.count}</font>
</body>