网站数据分析中就有一项是查看网站访问数目的,一般网站都会使用第三方统计软件的,其实,滨州邹平软件开发的工程师说,如果不用第三方提供的接口,那最好的解决方案应该是当SESSION建立时sessionCreated(),在访问总数和当前在线人数上+1
当SESSION销毁时sessionDistroyed(),在线人数-1
核心方法是利用Listener监听的各种接口
我把代码(主要部分)贴在下面
此段代码我亲自使用过,没有问题
但因为继承了接口,有些未使用的方法也要补充进去,具体方式比如在MyEclipse中可以靠点错误,ADD UNIMPLEMENTED METHOD实现
package com.eaie.system;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListener implements HttpSessionActivationListener,
HttpSessionListener, ServletContext, ServletRequestListener {
ServletContext context;
int onLineUserNum = 0;
int visitNum = 0;
HttpServletRequest request;
public void sessionDidActivate(HttpSessionEvent session) {
log("seesionDidActive("+session.getSession().getId()+")");
}
public void sessionWillPassivate(HttpSessionEvent session) {
log("seesionWillPassivate("+session.getSession().getId()+")");
}
public void sessionCreated(HttpSessionEvent event) {
onLineUserNum++;
visitNum ++;
String ip = request.getRemoteAddr();
log("sessionCreated('"+event.getSession().getId()+"'),-->IP:"+ip);
context.setAttribute("onLineUserNum", new Integer(onLineUserNum));
context.setAttribute("visitNum", new Integer(visitNum));
}
public void sessionDestroyed(HttpSessionEvent event) {
if (onLineUserNum>0){
onLineUserNum--;
}
String ip = request.getRemoteAddr();
log("sessionDestroyed('"+event.getSession().getId()+"'),-->IP:"+ip);
context.setAttribute("onLineUserNum", new Integer(onLineUserNum));
}
public void contextDestroyed(ServletContextEvent sce){
log("contextDestroyed-->ServletContext is destroyed");
this.context = null;
}
public void contextInitialized(ServletContextEvent sce){
this.context = sce.getServletContext();
log("contextDestroyed-->ServletContext is initialized");
}
public int getUserOnline(){
return this.onLineUserNum;
}
public void log(String message) {
PrintWriter out = null;