监听器实现页面点击率

chaicsd14 2010-04-26 09:33:31
有index.jsp 和1.jsp 两个JSP

我想用监听器统计1.jsp的统计量 但是不能用HttpSessionListener

请问下我这个监听器要怎么写啊?
...全文
128 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
sw19810913 2010-04-26
  • 打赏
  • 举报
回复
[code=Java]
//点击率,页面访问量统计,已应用在我的项目中
1、先创建CountFileHandler类
package com.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;

public class CountFileHandler {

public static void writerFile(String filename,long count){
try {
PrintWriter out = new PrintWriter(new FileWriter(filename));
out.println(count);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static long readFile(String filename){
File f = new File(filename);
long count = 0;
if (!f.exists()) {
writerFile(filename, 0);
}
try {
BufferedReader in = new BufferedReader(new FileReader(f));
count = Long.parseLong(in.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
count = 0;
}
return count;
}

public static String tranform(long count){ //123 "
String countNumber = ""+count;
String newString = "";
for(int i = 0 ; i<countNumber.length();i++){
newString = newString + "<img src='images\\"+countNumber.charAt(i)+".gif'>";
}
return newString;
}

}


2、在web.xml中配置
<!-- 统计在线人数 监听器-->
<listener>
<listener-class>com.listener.CountListener</listener-class>
</listener>

3、在jsp页面中显示,会在tomcat\webapps\项目名 目录下创建一个count.txt文件记录访问次数
<%
long count = CountFileHandler.readFile(request.getRealPath("/")+"count.txt");
if(session.getAttribute("visited") == null){
session.setAttribute("visited","y");
session.setMaxInactiveInterval(2);//设置失效时间,防止连续刷新
System.out.println("count:_"+count);
count = count + 1;
CountFileHandler.writerFile(request.getRealPath("/")+"count.txt",count);
//out.print(CountFileHandler.tranform(count));
}

%>
访问量:<%=CountFileHandler.tranform(count) %>

/code]
chaicsd14 2010-04-26
  • 打赏
  • 举报
回复
我要用监听器来实现啊
秋9 2010-04-26
  • 打赏
  • 举报
回复
使用单态模式可以做到,比如:

class Singleton
{
private int num=0;
private static Singleton instance = new Singleton();

private Singleton()
{
}

public static Singleton getInstance()
{
return instance;
}
public static add(){
num++;
}
public static getNum(){
return num;
}
}


海会圣贤 2010-04-26
  • 打赏
  • 举报
回复
mark

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧