package com.logistics.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.struts2.ServletActionContext;
/**
* @author weiwie
* 2012-4-16
*/
public class SessionListener extends HttpServlet implements HttpSessionListener{
private static final long serialVersionUID = 1L;
private static String path="";
private static Properties pp = new Properties();
private static Integer totalView = 0;//总访问量
private static Integer onlineNum ;//当前在线人数
public SessionListener() {
// TODO Auto-generated constructor stub
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("---------------------------------");
System.out.println("新创建了一个session,id="+arg0.getSession().getId());
totalView = totalView +1;
onlineNum = onlineNum+1;
System.out.println("当前总访问量为:"+totalView);
System.out.println("当前在线人数为:"+onlineNum);
System.out.println("---------------------------------");
arg0.getSession().getServletContext().setAttribute("totalView", totalView);
arg0.getSession().getServletContext().setAttribute("onlineNum", onlineNum);
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
System.out.println("---------------------------------");
System.out.println("清空了一个session");
onlineNum = (onlineNum-1)<0?0:(onlineNum-1);
System.out.println("当前总访问量为:"+totalView);
System.out.println("当前在线人数为:"+onlineNum);
System.out.println("---------------------------------");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
@Override
public void init() throws ServletException {
ServletContext servlet=this.getServletContext();
path=servlet.getRealPath("/")+"count.properties"; //服务器路劲
totalView=Integer.parseInt(this.readCount());//读取当前访问量
onlineNum = new Integer(0);//将当前在线人数置0
System.out.println("---------------------------------");
System.out.println("系统启动,总访问量:"+totalView);
System.out.println("---------------------------------");
}
public void writeCount(String count) {
pp.setProperty("count", count); // 设置键值对
try {
pp.store(new FileOutputStream(path), ""); // 写入文件
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String readCount() {
String count = "0";
File f = new File(path);
if (!f.exists()) {
writeCount("0");
}
try {
pp.load(new FileInputStream(path));
count = pp.getProperty("count");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
}