2013年(56)
分类: C#/.net
2013-10-09 14:46:27
在这里简单总结一下实现网页访问统计的几种方法:
1. 利用application对象进行统计,得到的效果是每进入一次该网页就统计一次。但效果不怎么好,因为一般统计网页访问量,刷新是不算进统计里的,这里就是这种缺点。
具体实现是:
[html]
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
if (application.getAttribute("count") == null) {
application.setAttribute("count", new Integer(0));
}
Integer count = (Integer) application.getAttribute("count");
application
.setAttribute("count", new Integer(count.intValue() + 1));
count = (Integer) application.getAttribute("count");
%>
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
if (application.getAttribute("count") == null) {
application.setAttribute("count", new Integer(0));
}
Integer count = (Integer) application.getAttribute("count");
application
.setAttribute("count", new Integer(count.intValue() + 1));
count = (Integer) application.getAttribute("count");
%>
2.为了解决上面的问题,有了另一种方法,就是同时利用application对象和session对象来统计,这种方法的原理是从打开浏览器到关闭浏览器算是访问一次,刷新、返回等操作不算做一次访问。但还是有缺陷,当jsp从新启动时,数据也被清零了。
下面还是具体实现:
[html]
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
int n = 0; String counter = (String)application.getAttribute("counter");
if(counter != null){
n = Integer.parseInt(counter);
}
if(session.isNew())
++n;
%>
<%
counter = String.valueOf(n);
application.setAttribute("counter", counter);
%>
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
int n = 0; String counter = (String)application.getAttribute("counter");
if(counter != null){
n = Integer.parseInt(counter);
}
if(session.isNew())
++n;
%>
<%
counter = String.valueOf(n);
application.setAttribute("counter", counter);
%>
3. 第三种方法是将统计数据在本地的文件当中,比如在一个txt文件当中。
这是为了解决重启之后数据不用担心会丢失。
创建一个类:JSPCount
[java]
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;
public class JSPCount {
//写入文件的方法
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;
}
}