Servlets Hits Counter - Java Servlets

What is Servlets Hits Counter?

Hit Counter for a Web Page

Several times you might be attentive in knowing entire number of hits on a specific page of your website. It is actually simple to count these hits using a servlet because the life cycle of a servlet is measured by the container in which it runs.

Resulting 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.
  • Rise global variable every time either doGet() or doPost() method is called.
  • If essential, 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 merely unique page hits with-in a session then you can use isNew() method to check if same page previously have been hit with-in that session. This step is elective.
  • You can show value of the global counter to show total number of hits on your web site. This step is also optional.

Here I'm supposing that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.

Example

This instance demonstrations how to implement a simple page hit counter –

Now let us compile above servlet and create resulting entries in web.xml

Currently call this servlet using URL http://localhost:8080/PageHitCounter. This would rise counter by one each time this page gets rested and it would show resulting effect −
Total Number of Hits

Numerous times you would be attentive in knowing total number of hits on your whole website. This is also exactly simple in Servlet and we can achieve these using filters.

Resulting are the steps to be taken to implement a simple website hit counter which is based on Filter Life Cycle −

  • Initialize a global variable in init() method of a filter.
  • Increase global variable every time doFilter method is called.
  • If required, you can use a database table to store the value of global variable in destroy() method of filter. This value can be read inside init() method when filter would be initialized next time. This step is optional.

Here I'm supposing that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.

Example

This instance shows how to implement a simple website hit counter –

Currently let us compile the overhead servlet and create the next entries in web.xml

Currently call any URL like URL http://localhost:8080/. This would rise counter by one each time any page gets a hit and it would show resulting message in the log –


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Servlets Topics