<%@ page contentType="text/html;charset=gb2312" %>
<!--jsp計數器-->
<%-- 以前學ASP時,用ASP做防止刷新的計數器很簡單,以下是一個用JSP做的計數器--%>
<html>
<head>
<title>jsp計數器</title>
</head>
<body>
<%@ page import="java.io.*" %>
<%
//out.println(request.getHeader("Cookie"));
String currentRecord = null;//保存文本的變量
BufferedReader file; //BufferedReader對象,用於讀取文件數據
String nameOfTextFile = "count.txt";
//讀取
file = new BufferedReader(new FileReader(nameOfTextFile));
String readStr =null;
int writeStr =0; //如果計數文本中的計數值為空則讓它顯示時變成1並寫入
try
{ readStr = file.readLine(); }
catch (IOException e)
{ System.out.println("讀取數據錯誤."); }
if (readStr == null) readStr = "沒有任何記錄";
//判斷cookie,第一次登陸時加1,刷新時不累計計數
else if (request.getHeader("Cookie")==null)
{ writeStr = Integer.parseInt(readStr)+1;}
else
{ writeStr = Integer.parseInt(readStr);}
//寫入時控制因為刷新引起的重復計數
if (request.getHeader("Cookie")==null)
{
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(writeStr);
pw.close();}
catch(IOException e) {
out.println(e.getMessage());}
}
%>
<p align="center">您是CNJSP的第<b><font color="red"><%=writeStr%></font></b>位客人。</p>
</body>
</html>