gpt4 book ai didi

java - 如何在 java 和 servlet 中按天计算网站点击率..?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:55 24 4
gpt4 key购买 nike

我有如下要求显示网站访问者数量:

  1. 访客总数
  2. 当天的访客总数。

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

这里是 Servlet 代码:

   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();
}
}
}
}
}

最佳答案

您应该使用数据库并根据当天更新计数器。

喜欢

Counter   Date
444 10-23-1998
555 10-24-1998

或者为当前日期文件创建单独的文件当前日期文件名,如 10-23-1998.txt 并更新当天的计数器。希望对您有所帮助。

关于java - 如何在 java 和 servlet 中按天计算网站点击率..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32179623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com