SessionListener类
public class SessionListener implements
HttpSessionAttributeListener {
public void
attributeAdded(HttpSessionBindingEvent event) {
if(event.getName().equals("userid"))
{
OnlineCount.allUser(event.getValue(),true);
}
}
public void
attributeRemoved(HttpSessionBindingEvent event) {
// TODO Auto-generated method
stub
if(event.getName().equals("userid"))
{
OnlineCount.allUser(event.getValue(),false);
}
}
public void
attributeReplaced(HttpSessionBindingEvent event) {
// TODO Auto-generated method
stub
}
}
OnlineCount类
public class OnlineCount {
private static List list = new ArrayList();
private
OnlineCount() {
}
//统计网站所有在线人数
public
static void allUser(Object object,boolean bl) {
//得到用户当前访问时间
String nowtime = getTime("mm:ss");
//Str数组用来存放用户的id和访问时间
String[] str = new String[2];
str[0] = object.toString();
str[1] = nowtime;
//temp数组用来临时存放从list里面取出的用户的id和访问时间
String[] temp = new String[2];
//循环list
for (int i = 0; i < list.size(); i++) {
temp = (String[])list.get(i);
//如果从list里面取出的用户ip和str里面存放的id相同,则更新访问时间
if(bl==false &&
temp[0].equals(str[0])) {
list.set(i,str);
return;
}
//如果监听类中穿过来bl==true,则认为不在线
if(bl==true &&
temp[0].equals(str[0]))
{
list.remove(i);
}
}
//添加一个新的在线用户
if(bl==false) list.add(str);
//释放资源
str = null;temp = null;
}
public
static int getOnlineAllCount() {
//返回当前在线人数
return list.size();
}
//返回所有在线人
public
static List getOnline() {
return list;
}
public
static int subTime(String src,String des) {
int n = 0;
java.util.Calendar ca = java.util.Calendar.getInstance();
long time1 =compareStringTime(src,des,"mm:ss");
ca.setTimeInMillis(time1);
n = (ca.get(java.util.Calendar.MINUTE)) * 60;
n = n + ca.get(java.util.Calendar.SECOND);
return n;
}
public
static String getTime(String parrten)
{
String timestr;
if(parrten==null||parrten.equals(""))
{
parrten="yyyyMMddHHmmss";
}
java.text.SimpleDateFormat sdf=new SimpleDateFormat(parrten);
java.util.Date cday=new Date();
timestr=sdf.format(cday);
return timestr;
}
public
static long compareStringTime(String t1,String t2,String
parrten)
{
SimpleDateFormat formatter = new SimpleDateFormat (parrten);
ParsePosition pos = new ParsePosition(0);
ParsePosition pos1 = new ParsePosition(0);
Date dt1=formatter.parse(t1,pos);
Date dt2=formatter.parse(t2,pos1);
long l=dt1.getTime()-dt2.getTime();
return l;
}
}
jsp页面
pageEncoding="utf-8"%>
import="com.ywh.common.OnlineCount"%>
String path = request.getContextPath();
String basePath =
request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
/p>
Transitional//EN">
href="">
My JSP 'index.jsp' startingpage
content="no-cache">
content="no-cache">
content="0">
content="keyword1,keyword2,keyword3">
content="This is my page">
String ip="";
if
(request.getHeader("x-forwarded-for") == null)
{
ip= request.getRemoteAddr();
}
else
{
ip=request.getHeader("x-forwarded-for");
}
OnlineCount.allUser(ip,false);
out.println("当前在线用户人数:"+OnlineCount.getOnlineAllCount()+"
"); %>
xml中的设置
com.ywh.common.SessionListener