java 统计在线人数(2)

首先给你讲一下,我的理解,人数统计好说,因为,可已设置监听器,让其在服务器启动的时候进行监听,然后统计登录人数,但是统计在线人数,就麻烦点了,因为大多数人都不愿意点击注销按钮,直接关闭浏览器,这样session的关闭就麻烦了点,我先给出统计人数的代码,我想统计在线人数可以定时调用程序来统计,但是不是实时的,所以最大的障碍就是怎么在关闭浏览器的时候,就关闭session
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ApplicationListener implements ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0) {
ServletContext sc = arg0.getServletContext();
Integer count = (Integer) sc.getAttribute("AccessCount");
try {
PrintWriter out = new PrintWriter(new FileWriter("c:/Users/god/count.txt"));// 将人数保存到文本文件
System.out.println("count:"+count);
out.print(count);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void contextInitialized(ServletContextEvent arg0) {
Integer count = 0;
ServletContext sc = arg0.getServletContext();

try {
Scanner in = new Scanner(new FileReader("c:/Users/god/count.txt"));// 读取已经产生的人数信息,然后进行累加
count = in.nextInt();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sc.setAttribute("AccessCount", count);
}
}

在web.xml文件里面进行设置
<listener>
<listener-class>
文件的位置也就是包名.ApplicationListener
</listener-class>
</listener>

统计的时候是设置拦截器,需要在struts.xml中设置

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

@SuppressWarnings("serial")
public class AccessInterceptor implements Interceptor{
private String id;
public void destroy() {

}

public void init() {

}

@SuppressWarnings("unchecked")
public String intercept(ActionInvocation ai) throws Exception {
ServletContext sc = ServletActionContext.getServletContext();
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
if(!session.getId().equals(id)){
Integer count = (Integer) sc.getAttribute("AccessCount");// 判断如果登录成功,统计数字自增
sc.setAttribute("AccessCount", count+1);
id = session.getId();
}
String result = ai.invoke();
return result;
}

}

你可能感兴趣的:(java 统计在线人数(2))