js|計數器|重新整理
<%@ 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>