|
計數(shù)器是一般網(wǎng)站必備的東東,別小看它了,每當站長看著小小計數(shù)器上的數(shù)字飛速增長的時候,感覺實在是好極了。以前我們用cgi、asp來寫計數(shù)器,這方面的文章很多了,在這里,我們將會采用目前比較流行的jsp技術(shù)演示如何做一個計數(shù)器。 其中我們用到了兩個文件,test.jsp文件用于在瀏覽器中運行,counter.java是后臺的一個小java bean程序,用來讀計數(shù)器的值和寫入計數(shù)器的值。而對于計數(shù)器的保存,我們采用了一個文本文件lyfcount.txt。
下面是詳細的程序代碼(test.jsp放到web目錄下,counter.java放到class目錄):
//test.jsp文件 <%@ page contentType="text/html;charset=gb2312"%> <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <TITLE>計數(shù)器演示程序</TITLE> </HEAD> <BODY> <!--創(chuàng)建并調(diào)用bean(counter)--> <jsp:useBean id="counter" class="counter" scope="request"> </jsp:useBean> <% //調(diào)用counter對象的ReadFile方法來讀取文件lyfcount.txt中的計數(shù) String cont=counter.ReadFile("/lyfcount.txt"); //調(diào)用counter對象的ReadFile方法來將計數(shù)器加一后寫入到文件lyfcount.txt中 counter.WriteFile("/lyfcount.txt",cont);%> 您是第<font color="red"><%=cont%></font>位訪問者 </BODY> </HTML>
//counter.java 讀寫文件的一個bean import java.io.*;
public class counter extends Object { private String currentRecord = null;//保存文本的變量 private BufferedReader file; //BufferedReader對象,用于讀取文件數(shù)據(jù) private String path;//文件完整路徑名 public counter() { } //ReadFile方法用來讀取文件filePath中的數(shù)據(jù),并返回這個數(shù)據(jù) public String ReadFile(String filePath) throws FileNotFoundException { path = filePath; //創(chuàng)建新的BufferedReader對象 file = new BufferedReader(new FileReader(path)); String returnStr =null; try { //讀取一行數(shù)據(jù)并保存到currentRecord變量中 currentRecord = file.readLine(); } catch (IOException e) {//錯誤處理 System.out.println("讀取數(shù)據(jù)錯誤."); } if (currentRecord == null) //如果文件為空 returnStr = "沒有任何記錄"; else {//文件不為空 returnStr =currentRecord; } //返回讀取文件的數(shù)據(jù) return returnStr; } //ReadFile方法用來將數(shù)據(jù)counter+1后寫入到文本文件filePath中 //以實現(xiàn)計數(shù)增長的功能 public void WriteFile(String filePath,String counter) throws
FileNotFoundException { path = filePath; //將counter轉(zhuǎn)換為int類型并加一 int Writestr = Integer.parseInt(counter)+1; try { //創(chuàng)建PrintWriter對象,用于寫入數(shù)據(jù)到文件中 PrintWriter pw = new PrintWriter(new FileOutputStream(filePath)); //用文本格式打印整數(shù)Writestr pw.println(Writestr); //清除PrintWriter對象 pw.close(); } catch(IOException e) { //錯誤處理 System.out.println("寫入文件錯誤"+e.getMessage()); } }
}
到這里,程序?qū)懲炅,將counter.java編譯為counter.class,同樣放在對應的
class目錄下,在根目錄下建立一個lyfcount.txt文件,文件內(nèi)容就一個數(shù)字0,直接在
瀏覽器中敲入地址就可以看到計數(shù)器了,刷新瀏覽器會看到不斷變幻的數(shù)字。 (如果運行時候提示找不到文件,請將上面test.jsp中的readfile那一句注釋后運行
一次則lyfcount.txt文件自動建立,然后就可以正常運行。)
|