jsp网站访问次数统计的几种方法(比较简单的几种)

本文探讨了使用jsp统计网站访问次数的简单方法,包括利用integer、application和session等技术进行计数。
摘要由CSDN通过智能技术生成
 
我采用的是jsp网页,但是不管采用什么语言,原理是一样的。最近在完善暑假做的一个简单年级网站,遇到很多问题。我想很多新手都会遇到这些问题,就把自己的心得体会分享给大家。因为我找到的解决方法,也是很多网友分享的。
    第一种,单页面统计。就是说,只要点击这个页面就会统计一次。
<%@ page contentType="text/html;charset=GB2312"  %> <html>  <head>   <title>   java计数器程序片    </title>   </head>   <body>    <%!//在这种标记中定义的变量为全局变量    int count=0;    synchronized void count(){    count++;    }    %>    <%    count();    out.println("这是第"+count+"个访问者!");    %>   </body> </html>

 第二中,是利用jsp的内置对象application进行统计。这个程序结果运行分析,
也是访问一次页面统计一次。感觉还是不够好。真正满意的是浏览器打开网页,
到关闭网页算一次,这样统计比较实际。
   
<%@ page contentType="text/html;charset=GB2312" %> <html>  <head>   <title>    java计数器程序   </title>  </head>  <body>   <%   if(application.getAttribute("count")==null){   application.setAttribute("count",new Integer(0));   }   Integer count=(Integer)application.getAttribute("count");      application.setAttribute("count",new Integer(count.intValue()+1));   count=(Integer)application.getAttribute("count");   %>   <center>这是第<%=count.intValue()%>个访问者!</center>  </body> </html>
第三中,利用jsp的application和session进行统计。它的原理是,
访问者打开浏览器到关闭浏览器算一次访问。
每次打开首页,创建一个session,这个session直到浏览器关闭才失效。
但总体来说,比前两种要好。
  但是有一个一个缺陷,那就是当jsp服务器重启时,累计的统计数就清零了。
<% int n=0; String count=(String)application.getAttribute("counter"); if(counter!=null) n=Integer.parseInt(counter); if(session.isNew()) ++n; out.print("你是第"+n+"位访客"); counter=String.valueOf(n); application.setAttribute("counter",counter); %> 
第四种方案,就是保存到txt文本中,那样重启服务器也不会丢失了。
写一个severlet
counter. java
package com.benb.servlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class counter {

public static void writeFile(String filename, long count) {

   try {
    PrintWriter out = new PrintWriter(new FileWriter(filename));
    out.println(count);
    out.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
}

public static long readFile(String filename) {
   File f = new File(filename);
   long count = 0;
   if (!f.exists()) {
    writeFile(filename, 0);
   }
   try {
    BufferedReader in = new BufferedReader(new FileReader(f));
    try {
     count = Long.parseLong(in.readLine());
    } catch (NumberFormatException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   }
   return count;
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值