統計在線人數-學習
阿新 • • 發佈:2018-04-20
統計在線人數-學習
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>
統計在線人數-學習