我要求网站访问者显示如下:
我已经完成了第一项要求。如何每天实施第二个..?
这里的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();
}
}
}
}
}
答案 0 :(得分:0)
声明一个变量计数器并在JSP中递增它。
当部署JSP并准备好其java文件时,该变量应被视为该java文件中的静态变量。因此,即使您重新加载文件,计数器也会递增。
这仅适用于所有计数器。 如果重新部署,则该值将丢失。然后是序列化或数据库选项。
或在web.xml中使用servlet init config参数。我目前没有与JSP联系。它的名字与上面提到的相同。