首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java和servlet中每天统计网站的命中次数..?

如何在java和servlet中每天统计网站的命中次数..?
EN

Stack Overflow用户
提问于 2015-08-24 10:06:32
回答 1查看 4.4K关注 0票数 3

我有以下要求显示网站访问者:

  1. 来访总人数
  2. 目前来访的总人数。

我已经完成了第一项要求。如何在每天的基础上实施第二次.?

在这里,Servlet代码:

代码语言:javascript
复制
   public class HitCounterServlet extends HttpServlet {

     String fileName = "D://hitcounter.txt";
     long hitCounter;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    readFile();
    updateHitCounterFile();
    HttpSession usersession = request.getSession();
    usersession.setAttribute("HITCOUNTER", hitCounter);
}

private void updateHitCounterFile() throws IOException {

    /**
     * Here I am increasing counter each time this HitCounterServlet is called. 
     * I am updating hitcounter.txt file which store total number of visitors on website.
     * Now I want total number of visitor on per day basis. 
    */

    hitCounter = hitCounter + 1;

    // read and update into file
    File file = new File(fileName);

    // if file doesnt exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(Long.toString(hitCounter));
    bw.close();
}

public void readFile() {
    BufferedReader br = null;
    String temp = "";
    try {
        br = new BufferedReader(new FileReader(fileName));
        while ((temp = br.readLine()) != null) {
            hitCounter = Long.parseLong(temp);
        }
        System.out.println("HIT Counter : " + hitCounter);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
 }
}
EN

回答 1

Stack Overflow用户

发布于 2015-08-24 10:23:41

声明一个变量计数器并在JSP.中增加它。

当部署JSP并准备其java文件时,该变量将被视为该java文件中的静态变量。因此,即使重新加载文件,计数器也会增加。

,这将只适用于所有计数器。如果您重新部署它,则此值将丢失。然后是序列化或DB选项。

或者在web.xml中使用servlet init配置参数。我目前没有与JSP联系。它的名字听起来和前面提到的一样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32179623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档