首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

网页计数器-代码

2012-09-10 
网页计数器---代码%@ page contentTypetext/html pageEncodingGBK%%@ page importjava.io.*%

网页计数器---代码

<%@ page contentType="text/html" pageEncoding="GBK"%><%@ page import="java.io.*"%><%@ page import="java.util.*"%><%@ page import="java.math.*"%><html><head><title>网站计数器</title></head><body><%!BigInteger count = null ;%><%!// 为了开发简便,将所有的操作定义在方法之中,所有的异常直接加入完整的try...catch处理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()) ;//将内容放到BigInteger类中}scan.close() ;} else {// 应该保存一个新的,从0开始count = new BigInteger("0") ;save(file,count) ;// 保存一个新的文件}}catch(Exception e){e.printStackTrace() ;}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){e.printStackTrace() ;}}%><%String fileName = this.getServletContext().getRealPath("/") + "count.txt";// 这里面保存所有的计数的结果File file = new File(fileName) ;if(session.isNew()){synchronized(this){count = load(file) ;// 读取count = count.add(new BigInteger("1")) ;// 再原本的基础上增加1。save(file,count) ;}}%><h2>您是第<%=count==null?0:count%>位访客!</h2></body></html>

析:

首先定义一个全局变量BigInteger,这样即使用户刷新页面,BigInteger对象也不会重复声明。分别定义了save()和load()方法,load()方法中首先判断文件是否存在,如果存在,则将已有内容读取进来;如果文件不存在,则创建一个新的count.txt(路径默认为web根目录中),并且将其中的内容设置为0.如果第一次访问,则要执行文件的更新操作,再同步代码块中首先对内容修改(让内容加1,由于使用的是BigInteger类,所以要使用其中的add()方法完成操作),然后将新的内容重新保存在文件中。

热点排行