servlet監聽器統計在線人數
阿新 • • 發佈:2017-08-16
stl value size str eth color request word element 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 class UserInfoListpublic 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 {UserInfoTrace implements HttpSessionBindingListenerprivate 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
<[email protected] import="java.util.Vector"%> <[email protected] import="com.listener.UserInfoTrace"%> <[email protected] 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>show.jsp
測試: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>test
servlet監聽器統計在線人數