servlet监听器统计在线人数
1.登录用户信息类
import java.util.Vector; public class UserInfoList { private static UserInfoList user = new UserInfoList(); private Vector vector = null; public UserInfoList() { this.vector = new Vector(); } public static UserInfoList getInstance() { return user; } public boolean addUserInfoList(String user) { if (user != null) { this.vector.add(user); return true; } else { return false; } } public Vector getList() { return this.vector; } public void removeUserInfo(String user) { if (user != null) { vector.removeElement(user); } } }
2.监听器类
import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import com.fmz.UserInfoList; public class UserInfoTrace implements HttpSessionBindingListener { private String user; private UserInfoList container = UserInfoList.getInstance(); public UserInfoTrace() { user = ""; } public void setUser(String user) { this.user = user; } public String getUser() { return this.user; } public void valueBound(HttpSessionBindingEvent arg0) { System.out.println("上线" + this.user); } @Override public void valueUnbound(HttpSessionBindingEvent arg0) { System.out.println("下线" + this.user); if (user != null) { container.removeUserInfo(user); } } }
3.后台show.jsp
<%@page import="java.util.Vector"%> <%@page import="com.listener.UserInfoTrace"%> <%@page import="com.fmz.UserInfoList"%> <%@ page language="java" pageEncoding="UTF-8"%> <!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <title>showUser</title> </head> <body> <% UserInfoList list = UserInfoList.getInstance(); UserInfoTrace ut = new UserInfoTrace(); String name = request.getParameter("name"); ut.setUser(name); session.setAttribute("list", ut); list.addUserInfoList(ut.getUser()); session.setMaxInactiveInterval(10); %> <textarea rows="8" cols="20"> <% Vector vector = list.getList(); if (vector != null && vector.size() > 0) { for (int i = 0; i < vector.size(); i++) { out.println(vector.elementAt(i)); } } %> </textarea> </body> </html>
测试:index.jsp(show.jsp页面显示的中文乱码未解决)
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>index</title> <style> input,p{ margin: 5px; padding: 3px; } </style> </head> <body> <form action="showUser.jsp" method="post" align="center"> nickname: <input type="text" name="name"><br> password: <input type="submit" value="submit" style="margin-left:100px "><br> </form> </body> </html>