Pr.Pg Next Pg

Hits Counter for single web page or Servlet tutorials

  • If you are a web Administrator of any web site than there will be a situation you want to know how many visitors have visited your web site and also how many time a single visitor have visited your site and web page.

  • 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.

  • Below are the steps to be taken to implement a simple page hit counter which is based on Servlet Life Cycle:

    1. Initialize a class level variable in init() method.

    2. Increase global variable every time either doGet() or doPost() method is called.

    3. 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.

    4. 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.

    5. You can display value of the global counter to show total number of hits on your web site. This step is also optional.



Example: Servlet program to show the page hit counter

Sam Sir

//Program name

// Program to show the page hit counter




import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class SimpleCounterServlet extends HttpServlet


private int HitCounter;

public void init() throws ServletException


HitCounter = 0;


public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException


PrintWriter out = response.getWriter();

out.println("<h2>Welcome to</h2>");

out.println("Hits on this servlet so far: "+ (++HitCounter));


public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException


doGet(request, response);




Hit Counter in servlets

Pr.Pg border                                              Next Pg