当前位置: 移动技术网 > IT编程>开发语言>Java > jsp计数器制作

jsp计数器制作

2017年12月12日  | 移动技术网IT编程  | 我要评论
计数器是一般网站必备的东东,别小看它了,每当站长看着小小计数器上的数字飞速增长的时候,感觉实在是好极了。以前我们用cgi、asp来写计数器,这方面的文章很多了,在这里,我们将会采用目前比较流行的jsp技术演示如何做一个计数器。
其中我们用到了两个文件,test.jsp文件用于在浏览器中运行,counter.java是后台的一个小java bean程序,用来读计数器的值和写入计数器的值。而对于计数器的保存,我们采用了一个文本文件lyfcount.txt。


下面是详细的程序代码(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>计数器演示程序</title>
</head>
<body>
<!--创建并调用bean(counter)-->
<jsp:usebean id="counter" class="counter" scope="request">
</jsp:usebean>
<%
//调用counter对象的readfile方法来读取文件lyfcount.txt中的计数
string cont=counter.readfile("/lyfcount.txt");
//调用counter对象的readfile方法来将计数器加一后写入到文件lyfcount.txt中
counter.writefile("/lyfcount.txt",cont);%>
您是第<font color="red"><%=cont%></font>位访问者
</body>
</html>

//counter.java 读写文件的一个bean
import java.io.*;

public class counter extends object {
private string currentrecord = null;//保存文本的变量
private bufferedreader file; //bufferedreader对象,用于读取文件数据
private string path;//文件完整路径名
public counter() {
}
//readfile方法用来读取文件filepath中的数据,并返回这个数据
public string readfile(string filepath) throws filenotfoundexception
{
path = filepath;
//创建新的bufferedreader对象
file = new bufferedreader(new filereader(path));
string returnstr =null;
try
{
//读取一行数据并保存到currentrecord变量中
currentrecord = file.readline();
}
catch (ioexception e)
{//错误处理
system.out.println("读取数据错误.");
}
if (currentrecord == null)
//如果文件为空
returnstr = "没有任何记录";
else
{//文件不为空
returnstr =currentrecord;
}
//返回读取文件的数据
return returnstr;
}
//readfile方法用来将数据counter+1后写入到文本文件filepath中
//以实现计数增长的功能
public void writefile(string filepath,string counter) throws

filenotfoundexception
{
path = filepath;
//将counter转换为int类型并加一
int writestr = integer.parseint(counter)+1;
try {
//创建printwriter对象,用于写入数据到文件中
printwriter pw = new printwriter(new fileoutputstream(filepath));
//用文本格式打印整数writestr
pw.println(writestr);
//清除printwriter对象
pw.close();
} catch(ioexception e) {
//错误处理
system.out.println("写入文件错误"+e.getmessage());
}
}

}

到这里,程序写完了,将counter.java编译为counter.class,同样放在对应的

class目录下,在根目录下建立一个lyfcount.txt文件,文件内容就一个数字0,直接在

浏览器中敲入地址就可以看到计数器了,刷新浏览器会看到不断变幻的数字。
(如果运行时候提示找不到文件,请将上面test.jsp中的readfile那一句注释后运行

一次则lyfcount.txt文件自动建立,然后就可以正常运行。)



如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网