我有以下要求显示网站访问者:
我已经完成了第一项要求。如何在每天的基础上实施第二次.?
在这里,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();
}
}
}
}
}发布于 2015-08-24 10:23:41
声明一个变量计数器并在JSP.中增加它。
当部署JSP并准备其java文件时,该变量将被视为该java文件中的静态变量。因此,即使重新加载文件,计数器也会增加。
,这将只适用于所有计数器。如果您重新部署它,则此值将丢失。然后是序列化或DB选项。
或者在web.xml中使用servlet init配置参数。我目前没有与JSP联系。它的名字听起来和前面提到的一样。
https://stackoverflow.com/questions/32179623
复制相似问题