Posted on 2008-09-10 14:54
semovy 阅读(234)
评论(0) 编辑 收藏 所属分类:
JSP
<%@ page contentType="text ml;charset=gb2312"%>
<%@ page language="java" import="java.io.*"%>
<html>
<head>
<meta http-equiv="content-type" content="text ml; charset=gb2312">
<title>计数器</title>
</head>
<%!
//同步更新计数器
synchronized void counter(){
ServletContext application=getServletContext(); //构造application对象(可选)
String szpath=application.getRealPath("/"); //得到当前路径
szpath=szpath+"hits.txt"; //计数器文档 0-9999999999999...
String szrecord=""; //记数 string
int nrecord=0; //记数 int
try{
BufferedReader file=new BufferedReader(new FileReader(szpath));
szrecord=file.readLine(); //读取计数器文档
}
catch(IOException e){
e.printStackTrace(System.err);
}
if(szrecord==null) szrecord="0"; //假如计数器文档为空
nrecord=java.lang.Integer.parseInt(szrecord)+1; //计数器+1
try{
File f=new File(szpath);
PrintWriter pw=new PrintWriter(new FileWriter(f));
pw.print(nrecord); //写文档
pw.close();
}
catch(IOException e){
System.out.println(e);
}
}
%>
<%
//显示计数器
if(session.isNew()){ //假如是新用户
counter();
}
String path=application.getRealPath("/");
String szpath=path+"hits.txt";
String szrecord="";
BufferedReader file=new BufferedReader(new FileReader(szpath));
try{
szrecord=file.readLine();
}
catch(IOException e){
System.out.println("文档未找到!");
}
//显示7位数字gif图像
String szout="<body topmargin=0 leftmargin=0>";
int i=0;
int k=7-szrecord.length(); //"0"的个数
for (i=0;i<k-1;i++){ //显示"0"
szout=szout+"<img src=images/0.gif>";
}
for (i=0;i<szrecord.length();i++){ //显示非"0"
szout=szout+"<img src=images/"+ szrecord.charAt(i) +".gif>";
}