67,512
社区成员
发帖
与我相关
我的任务
分享
package com.looveh.demo1;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class OnlineCountListener implements HttpSessionListener {
public int count = 0;
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("session created");
count++;
httpSessionEvent.getSession().getServletContext().setAttribute("count",count);
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("session destroyed");
count--;
httpSessionEvent.getSession().getServletContext().setAttribute("count",count);
}
}
<%@page language="java" pageEncoding="utf-8" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<h2>Hello World!</h2>
在线人数:<%=application.getAttribute("count")%>
</body>
</html>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>com.looveh.demo1.OnlineCountListener</listener-class>
</listener>
</web-app>