您的位置:首页 > 图文教程 > 一个可以防止刷新的JSP计数器 返回首页

一个可以防止刷新的JSP计数器

时间:2011-12-02 16:49:39  作者:彭老师

Pro/E5.0产品设计视频教程_软件自学网  AutoCAD2011机械视频教程_软件自学网

<%@ 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>

  
上一个教程:jsp文件操作之写入篇
下一个教程:JSP页面中的pageEncoding和contentType两种属性的区别