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