在一些博客或論壇裏經常出現一些訪問次數的字樣,這就是通常說的網站計數器。進行網站計數器開發需要注意以下3個問題:
1、網站的來訪人數很多,所以必須用大整數來表示;
2、每個用戶在第一次訪問時需要計數,重複刷新頁面不應該重複計數;
3、對網站訪問量計數值的修改屬於多線程操作,需要進行同步操作。
編寫的模擬網站計數器的jsp代碼如下所示:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.io.*"%> <%--由於要使用IO操作,必須導入java.io包--%>
<%@ page import="java.util.*"%> <%--Scanner在java.util中定義--%>
<%@ page import="java.math.*"%> <%--BigInteger定義在java.math中--%>
<html>
<head>
<title>網站計數器</title>
</head>
<body>
<%!
BigInteger count = null;
%>
<%!//以下方法爲了省事,直接在方法中處理了異常,而實際中要交給調用處處理
public BigInteger load(File file) { //讀取計數文件
BigInteger count = null; //讀取接受的數據
try {
if(file.exists()) {
Scanner scan = null;
scan = new Scanner(new FileInputStream(file)); //從文件中讀取
if(scan.hasNext()) {
count = new BigInteger(scan.next()); //將內容放到BigInteger中
}
scan.close(); //關閉輸入流
} else {
count = new BigInteger("0"); //第一次訪問
save(file,count);
}
} catch(Exception e) {
e.printStackTrace();
}
return count; //返回讀取後的數據
}
public void save(File file,BigInteger count) {
try {
PrintStream ps = null; //定義輸出流對象
ps = new PrintStream(new FileOutputStream(file)); //打印流對象
ps.println(count);
ps.close();
} catch(Exception e) {
e.printStackTrace();
}
}
%>
<%
String fileName = this.getServletContext().getRealPath("/") + "count.txt"; //文件路徑
File file= new File(fileName);
if(session.isNew()) {
synchronized(this) {
count = load(file);
count = count.add(new BigInteger("1")); //自增操作
save(file,count);
}
}
%>
<h3>你是第<%=count==null?0:count%>位訪客</h3> <%--輸出內容--%>
</body>
</html>
這段代碼的運行結果爲:
當第一次訪問這個頁面顯示“你是第1位訪客”,刷新頁面顯示不變,如下圖所示;
關閉瀏覽器用新的瀏覽器打開這個頁面時顯示“你是第2位訪客”,如下圖所示: