Reputation: 133
I have the requirement to show website visitors count as follow:
I have done first requirement . How to implement second one on per day basis..?
Here Servlet Code :
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();
}
}
}
}
}
Upvotes: 3
Views: 4709
Reputation: 777
Declare a variable counter and increment it in JSP.
When JSP is deployed and its java file is prepared, this variable shall be treated as static variable in that java file. So even if you reload the file, counter will increment.
This will work only for over all counter. If you redeploy it, this value shall be lost. Then there comes the serialization or DB options.
Or Use a servlet init config parameter in your web.xml. I am not in touch with JSPs currently. Its name sounds same as mentioned.
Upvotes: 0
Reputation: 5157
You should use database & update the counter with current day basis.
like
Counter Date
444 10-23-1998
555 10-24-1998
Or create separate file for current date file current date file name like 10-23-1998.txt
& update the counter for that day. Hope it helps.
Upvotes: 1