Servlet监听器统计在线人数

2020-11-26  本文已影响0人  Jianbaozi
image.png image.png

UserInfo

package com.baozi;

import java.util.Vector;

public class UserInfo {
    @SuppressWarnings("rawtypes")
    private Vector vec=new Vector();
    private static UserInfo user=new UserInfo();
    @SuppressWarnings("rawtypes")
    public UserInfo(){
        vec=new Vector();
    }
    public static UserInfo getInstance(){
        return user;
    }
    @SuppressWarnings("unchecked")
    public boolean addUserInfo(String user){
        if(user!=null){
            vec.addElement(user);
            return true;
        }
        return false;
    }
    @SuppressWarnings("rawtypes")
    public Vector getUserInfo(){
        return vec;
    }
    public void removeUserInfo(String user){
        vec.removeElement(user);
    }
    
}

UserInfoTrace

package com.baozi;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class UserInfoTrace implements HttpSessionBindingListener {
    private String user;
    private UserInfo uinf=UserInfo.getInstance();
    public void setUser(String user){
        this.user=user;
    }
    public String getUser(){
        return user;
    }
    public void valueBound(HttpSessionBindingEvent arg0) {
        System.out.println("上线"+user);
    }
    public void valueUnbound(HttpSessionBindingEvent arg0) {
        System.out.println("下线"+user);
        if(user!="")
            uinf.removeUserInfo(user);
            
    }
}

index.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312" isErrorPage="true"%>
<%request.setCharacterEncoding("gb2312"); %>
<%@page import="com.baozi.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>问卷调查</title>
</head>
<body>
<form action="showUser.jsp" method="post">
    用户名<input name="user" type="text"><br>
    <input type="Submit" type="submit" value="登录">
</form>
</body>
</html>

showuser.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.util.*" %>
<%@ page import="com.baozi.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>在线信息</title>
</head>
<%
session.setMaxInactiveInterval(10);
UserInfo list=UserInfo.getInstance();
UserInfoTrace ut=new UserInfoTrace();
String name=request.getParameter("user");
ut.setUser(name);
session.setAttribute("list",ut);
list.addUserInfo(ut.getUser());
%>
<textarea rows="8" cols="20">
<%Vector vec=list.getUserInfo();
if(vec!=null&&vec.size()>0){
    for(int i=0;i<vec.size();i++)
    out.println(vec.elementAt(i));
}
%>
</textarea>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读