实现网站计数器

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page contentType="text/html; charset=GBK" %>
<%@page import="java.math.BigInteger"%>
<%@page import="java.io.File"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.PrintStream"%>
<%@page import="java.io.FileOutputStream"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>网站计数器</title>
</head>

<body>
<%!
BigInteger count
= null;
%>
<%!
public BigInteger load(File file){
BigInteger count
= null;
try{
if(file.exists()){
Scanner scan
= new Scanner(new FileInputStream(file));
if(scan.hasNext()){
count
= new BigInteger(scan.next());
}
scan.close();
}
else{
count
= new BigInteger("0");
save(file, count);
}
}catch (Exception e){
System.out.println(e);
}
return count;
}
public void save(File file, BigInteger count){
try{
PrintStream ps
= null;
ps
= new PrintStream(new FileOutputStream(file));
ps.println(count);
ps.close();
}catch (Exception e){
System.out.println(e);
}
}
%>
<%
System.out.println(
"count=========" + count);
String fileName = this.getServletContext().getRealPath("/") + "count.txt";
File file
= new File(fileName);
if(session.isNew()){
synchronized(this){
count
= load(file);
System.out.println(
"count=========" + count);
count
= count.add(new BigInteger("1"));
save(file, count);
System.out.println(
"count=========" + count);
}
}
%>
<h2>您是第<%=count == null ? 0 : count %>位访客</h2>
</body>
</html>

posted @ 2011-10-19 19:40  lihui_yy  阅读(700)  评论(0编辑  收藏  举报