Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

Hit counter for JSP servlet web application


There are many free nice and simple hit counters available out there. However they are not totally free as you will also have some kind of hidden url to the external website/resource within it.

If you want you can implement such counter yourself within JSP file in a no time :)

One of the simplest way is to just do it within the JSP file with no core java work:
1. Use application attribute within your JSP file:
    Integer counter = (Integer) application.getAttribute("counter");
    if(counter == null || counter == 0) {
       counter = 1; // initial value
    } else {
       counter += 1;
    application.setAttribute("counter", counter);

2. Then just show it: <%= counter%>

Instead of storing it in application attribute you could declare it as a static field. As you know static fields in programming are generally shared across all instances of an object.

Note that we are not storing the actual value of the counter in the datastore. It means everytime the application server is restarted the counter returns to the initial value.

It shouldn't be a problem because usually you restart an  app when you want to upload a new version anyway. In that case you can set the counter to the last known value instead of "1" in the new code.