以下代码实现了一个jsp计数器,有防止刷新的功能,供大家学习参考。
//读取
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">您是第<b><font color="red"><%=writeStr%></font></b>位访客。</p>
</body>
</html>