javaWeb之-------统计网站刷新量

来源:互联网 发布:大奖章基金骗局知乎 编辑:程序博客网 时间:2024/06/05 05:15

每个网站都有自己的统计访问量,但是少不了服务器会出现意外情况,(如断电。。)

所以就需要我们在网站挂机的前段时间将这个数据存起来。我们就需要用到网站最大的容器,application,我们采用观察者设计模式实现ServletContextListener接口。然后在销毁之前将这个数据存起来

ps:属于点点知识,大牛请绕道。

开发步骤:

第一步:实现ServletContextListener接口。
第二步:实现两个方法。
contextInitialized
contextDestroyed
第三步:在web.xml中添加节点。

具体实现:

我们需要实现ServletContextListener接口,里面用两个方法,我们需要在初始化的时候从文件里面读出来,然后在销毁的时候存进去。

读取文件:

public class MyServletContext implements ServletContextListener {  //这是监听器,统计网站的访问量  /*   * 启动的时候(初始化)从文件里读取,存在servletcontext中   * 销毁的时候,把数据从servletcontext中取出来,存到文件里   */      String filename ="";      @Override      public void contextInitialized(ServletContextEvent sce) {          ServletContext context=sce.getServletContext();          String filename=context.getRealPath("/count.txt");          try {              BufferedReader br =new BufferedReader(new FileReader(filename));              String num =br.readLine();              Integer numer =Integer.valueOf(num);              context.setAttribute("count", numer);//将读取的值存放到servletcontext容器中              br.close();          } catch( Exception e) {              e.printStackTrace();              context.setAttribute("count", new Integer(0));//出异常说明没有值读取,所以设置为0;          }      }  

销毁将数据存储到文件(只有文件才是永久储存)

@Override      public void contextDestroyed(ServletContextEvent sce) {          ServletContext context=sce.getServletContext();          String filename=context.getRealPath("/count.txt");          try {              PrintWriter pw =new PrintWriter(filename);              Integer count=(Integer) context.getAttribute("count");//从容器中获取相应count值  //          pw.write(count);//存的文件tomcat目录下              pw.print(count);              System.out.println("销毁了"+count);              pw.close();          } catch (FileNotFoundException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }      }  

访问量的添加

访问量我们需要写在过滤器里面,每次过滤一次我们从context中加一次

public void doFilter(ServletRequest request, ServletResponse response,          FilterChain chain) throws IOException, ServletException {      //这里考虑到多线程,这样写数据不准确,所以需要采用多线程      final ServletContext sct=request.getServletContext();      //启用新的线程去计数,不影响整个网站的速度,这样做很好      new Thread(){          public void run(){              MyCount.addcount(sct);//把下面这个整体上锁。。          }      }.start();      chain.doFilter(request, response);  }  

统计数量会存在多线程的问题,所以我们采用多线程处理,只让统计数量线程,不影响整个网站的效率

//把这个上锁,只会子分支会慢,不会影响整个网站的速度  class MyCount{      public synchronized static void  addcount(ServletContext sct){          Integer count=Integer.parseInt(""+sct.getAttribute("count"));          count++;//添加之后,我们需要添加容器里面进去          sct.setAttribute("count", count);          System.out.println(count);      }  }  

MyServletContext在初始化的时候会从文件中载入,不存在会自动设置为一,每过一次filter,就会加1,这就实现了网站刷新量的统计。