java 統計網站訪問量

轉:

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.PipedWriter;
import java.io.PrintWriter;

public class CountPerson {

//保存訪問量,這樣就不會出現從起tomcat訪問量就從0算起
 public static void saveCount(String fileName,long count){
  try {
   PrintWriter out = new PrintWriter(new FileWriter(fileName));
   out.print(count);
   out.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

//讀出訪問量
 public static long replaceCount(String fileName){
  long count =0;
  File file = new File(fileName);
  if(!file.exists()){
   saveCount(fileName,0);
  }
  try {
   BufferedReader bur = new BufferedReader(new FileReader(file));
   count = Long.parseLong(bur.readLine());
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
   count=0;
  }
  return count;
 }

//用圖片顯示訪問量,有0-9個.gif圖片
 public static String  drawingCount(long count){
  String str = ""+count ;
  String img = "";
  for(int i=0;i<str.trim().length();i++){
   img = img+"<img src='images\\"+str.charAt(i)+".gif'>";
  }
  return img;
 }
}

-------------------------------------------------------------------

jsp顯示頁面

<html>

<head>

  </head>
    <%
     long count = CountPerson.replaceCount(request.getRealPath("/")+"count.txt");
    if(session.getAttribute("CHEN_CHAO")==null){
     session.setAttribute("CHEN_CHAO","123");
     session.setMaxInactiveInterval(60*60*24);
    count = count+1;
    CountPerson.saveCount(request.getRealPath("/")+"count.txt",count);
 }
  %>
  <body>
 <h3>該Web應用自起動訪問量: <%=CountPerson.drawingCount(count) %></h3>

</body>

</html>

 

忘了說。。在目錄下面會有一個count.txt的文本文件,裏面記錄的是訪問數量(可以修改的)。。當要重新部署項目時要記得把這文件複製過去。

就如同上傳文件的附近一樣。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章