Many times you would be interested in knowing total number of hits on a particular page of your website. It is very simple to count these hits using a servlet because the life cycle of a servlet is controlled by the container in which it runs.
Following are the steps to be taken to implement a simple page hit counter which is based on Servlet Life Cycle:
- Initialize a global variable in init() method.
- Increase global variable every time either doGet() or doPost() method is called.
- If required, you can use a database table to store the value of global variable in destroy() method. This value can be read inside init() method when servlet would be initialized next time. This step is optional.
- If you want to count only unique page hits with-in a session then you can use isNew() method to check if same page already have been hit with-in that session. This step is optional.
- You can display value of the global counter to show total number of hits on your web site. This step is also optional.
Here I’m assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.
This example shows how to implement a simple page hit counter:
Now call this servlet using URL http://localhost:8080/NumberOfHits. This would increase counter by one every time this page gets refreshed and it would display following result:
Total Number of Hits