清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
onLineUser.java 继承HttpSessionBindingListener实现在线人数记录功能
package com.trs;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;
/**
*HttpSessionBindingListener接口有两方需要实现的方法:
*public synchronized void valueBound(HttpSessionBindingEvent httpsessionbindingevent)
*public synchronized void valueUnbound(HttpSessionBindingEvent httpsessionbindingevent)
*Session创建的时候Servlet容器将会调用valueBound方法;Session删除的时候则调用valueUnbound方法.
*/
public class onLineUser implements HttpSessionBindingListener
{
public onLineUser()
{
}
//保存在线用户的向量
private Vector users=new Vector();
//得到用户总数
public int getCount()
{
users.trimToSize();
return users.capacity();
}
//判断是否存在指定的用户
public boolean existUser(String userName)
{
users.trimToSize();
boolean existUser=false;
for (int i=0;i
{
if (userName.equals((String)users.get(i)))
{
existUser=true;
break;
}
}
return existUser;
}
//删除指定的用户
public boolean deleteUser(String userName)
{
users.trimToSize();
if(existUser(userName))
{
int currUserIndex=-1;
for(int i=0;i
{
if(userName.equals((String)users.get(i)))
{
currUserIndex=i;
break;
}
}
if (currUserIndex!=-1)
{
users.remove(currUserIndex);
users.trimToSize();
return true;
}
}
return false;
}
//得到当前在线用户的列表
public Vector getOnLineUser()
{
return users;
}
public void valueBound(HttpSessionBindingEvent e)
{
users.trimToSize();
if(!existUser(e.getName()))
{
users.add(e.getName());
System.out.print(e.getName()+"\t 登入到系统\t"+(new Date()));
System.out.println(" 在线用户数为:"+getCount());
}else
System.out.println(e.getName()+"已经存在");
}
public void valueUnbound(HttpSessionBindingEvent e)
{
users.trimToSize();
String userName=e.getName();
deleteUser(userName);
System.out.print(userName+"\t 退出系统\t"+(new Date()));
System.out.println(" 在线用户数为:"+getCount());
}
}
logout.jsp
<%@ page contentType="text/html;charset=GB2312" pageEncoding="GBK"%>
<%@ page import="com.trs.onLineUser,java.util.*" %>
<jsp:useBean id="onlineuser" class="com.trs.onLineUser" scope="application"/>
<html>
<head>
<title>show</title>
</head>
<body>
<%
String name=(String)session.getValue("name");
if(name!=null && name.length()!=0)
{
if(onlineuser.deleteUser(name))
out.println(name+"已经退出系统!");
else
out.println(name+"没有登陆到系统!");
}
%>
</body>
</html>
online.jsp
<%@ page contentType="text/html;charset=GB2312" pageEncoding="GBK"%>
<%@page import="com.trs.onLineUser,java.util.*" %>
<html>
</body>
<%
String name=request.getParameter("name");
String password=request.getParameter("password");
if(name!=null && password!=null)
{
Cookie cookie1=new Cookie("name", name);
cookie1.setMaxAge(100000);
response.addCookie(cookie1);
Cookie cookie2=new Cookie("password", password);
cookie2.setMaxAge(100000);
response.addCookie(cookie2);
out.println("完成书写Cookie!");
}
else
{
out.println("书写失败!");
}
%>
</body>
</html>
需要说明的是这种方式适合只有单台服务器的小网站使用,如果网站有多台web server则不能使用这种方式记录在线人数。