JSP中实现网页访问统计的方法(7)
return count;
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
public class Counter extends HttpServlet{
//写入文件的方法
public static void write2File(String filename, long count){
try{
PrintWriter out = new PrintWriter(new FileWriter(filename));
out.println(count);
out.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
//读文件的方法
public static long readFromFile(String filename){
File file = new File(filename);
long count = 0;
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
write2File(filename, 0);
}
try{
BufferedReader in = new BufferedReader(new FileReader(file));
try{
count = Long.parseLong(in.readLine());
}
catch (NumberFormatException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
}
return count;
}
}
jsp文件代码:
[plain]
<%@page import="org.servlet.count.Counter"%>
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<html>
<head>
<title>java 计数器程序</title>
</head>
<body>
<%
Counter CountFileHandler = new Counter();
long count = 0;
if(application.getAttribute("count") == null){
count = CountFileHandler.readFromFile(request.getRealPath("/") + "count.txt");
相关新闻>>
- 发表评论
-
- 最新评论 更多>>