When implementing a hit counter, there are many decisions to make.
- Are you sure you want to write it yourself?
There are many free web-based hit counters out there that take care of a lot of the hassles for you. Most seem to serve up a GIF so you can embed it in your page as an IMG or JavaScript. See:
- How can I add a counter applet to my web page?
- http://www.theCounter.com
- http://www.jcount.com
- http://counter.bloke.com
- What do you want to count?
The most common thing to count is individual hits to your site's home page, via an IMG reference (see below). You may instead want to count unique new user sessions (see the API for HttpSession for information on setting up a listener that listens for new sessions), or some other factor.
- Where do you want to save the data?
Servlets are transient. If you want your hit count to last past a server restart, you need to save it somewhere. This means using either a file system or a database.
- How do you want to display the results?
You can either display the results as an image, or as embedded text or HTML. See below for information on image-based hit counters. To use embedded text, the easiest way is to write your hit counter as a JavaBean, with separate methods for incrementing the count and returning the current count. Then you can instantiate the bean, place it in the application context, and access it from any servlet using code like:
HitCounter h = (HitCounter)getServletContext().getAttribute("hitcounter");
h.incrementCount();
out.print(h.getCount());
Returning an image simplifies some aspects of the system but means you have to deal with creating an offscreen image and rendering the text inside it.
You may also want to make your hit counter be an applet.