在Eclipse(J2EE)项目中新建动态Web工程
添加下面的java文件,源码清单如下
package com.kagula;
import java.io.*;
public class counter extends Object {
private String currentRecord = null;// 保存文本的变量
private BufferedReader file; // BufferedReader对象,用于读取文件数据
private String path;// 文件完整路径名
public counter() {
}
public String ReadFile(String filePath) throws FileNotFoundException {
path = filePath;
file = new BufferedReader(new FileReader(path));
String returnStr = null;
try {
currentRecord = file.readLine();
} catch (IOException e) {
System.out.println("读取数据错误.");
}
if (currentRecord == null)
returnStr = "没有任何记录";
else {
returnStr = currentRecord;
}
return returnStr;
}
public void WriteFile(String filePath, String counter) throws
FileNotFoundException {
path = filePath;
int Writestr = Integer.parseInt(counter) + 1;
try {
//我是servlet工程,这段代码在bean里面,Eclipse中测试,发现如果filepath="/lyfcount.txt",
//则文件在JavaWorkspace所在分区的根目录!,例如d:/lyfcount.txt。
PrintWriter pw = new PrintWriter(new FileOutputStream(filePath));
pw.println(Writestr);
pw.close();
} catch (IOException e) {
System.out.println("写入文件错误" + e.getMessage());
}
}
}
jsp中引用bean,bean必须在package中,示例代码如下(注意com.kagula.counter):
<%@ 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="com.kagula.counter" scope="request">
</jsp:useBean>
<%
String cont=counter.ReadFile("/lyfcount.txt");//当前分区根目录
counter.WriteFile("/lyfcount.txt",cont);%>
您是第<font color="red"><%=cont%></font>位访问者
</BODY>
</HTML>
然后,通过“http://localhost:8080/SimpleCounter/counter.jsp”访问,可以查看Web客户端是否在缓存问题。