import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
if(session.isNew()){
ServletContext context = session.getServletContext();
//第几个访问者
Integer caller = (Integer) context.getAttribute("caller");
//在线人数
Integer counter = (Integer) context.getAttribute("counter");
if(caller==null){
caller = 1;
}else{
caller++;
}
if(counter==null){
counter = 1;
}else{
counter++;
}
context.setAttribute("counter",counter);
session.setAttribute("caller",counter);
}
}
public void sessionDestroyed(HttpSessionEvent se) {
}
}
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
你是第${caller}访问者<br/>
当前在线${counter}人<br/>
</body>
</html>
![](http://i2.51cto.com/images/blog/201804/20/c27303a56977a98b0ec969390a9745ed.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)