Easy Tutorial
❮ Servlet Handling Date Servlet Debugging ❯

Servlet Click Counter

Web Page Click Counter

Many times, you might be interested in knowing the total number of clicks on a specific page of your website. Using a Servlet to count these clicks is quite simple because the lifecycle of a Servlet is controlled by the container it runs in.

Here are the steps to implement a simple web page click counter based on the Servlet lifecycle:

Here, we assume that the Web container will not be restarted. If it is restarted or the Servlet is destroyed, the counter will be reset.

Example

This example demonstrates how to implement a simple web page click counter:

package com.tutorialpro.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PageHitCounter
 */
@WebServlet("/PageHitCounter")
public class PageHitCounter extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private int hitCount; 

    public void init() 
    { 
        // Reset hit counter
        hitCount = 0;
    } 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        // Increment hitCount
        hitCount++; 
        PrintWriter out = response.getWriter();
        String title = "Total Clicks";
        String docType = "<!DOCTYPE html> \n";
        out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "&lt;body bgcolor=\"#f0f0f0\">\n" +
            "&lt;h1 align=\"center\">" + title + "</h1>\n" +
            "&lt;h2 align=\"center\">" + hitCount + "</h2>\n" +
            "</body></html>");
    }

    public void destroy() 
    { 
        // This step is optional, but if needed, you can write the hitCount value to a database
    } 

}

Now, let's compile the above Servlet and create the following entry in the web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>PageHitCounter</servlet-name>
<servlet-class>com.tutorialpro.test.PageHitCounter</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PageHitCounter</servlet-name>
    <url-pattern>/TomcatTest/PageHitCounter</url-pattern>
  </servlet-mapping>
</web-app>

Now, invoke this Servlet by accessing http://localhost:8080/TomcatTest/PageHitCounter. This will increment the counter value by 1 each time the page is refreshed, and the result will be shown as follows:

| Total Hits 6 |

Website Hit Counter

Many times, you might be interested in knowing the total number of hits of the website. This is very simple to do in a Servlet, and we can achieve this by using a filter.

The following are the steps to implement a simple filter-based website hit counter:

Here, we assume that the web container will not be restarted. If it is restarted or the Servlet is destroyed, the hit counter will be reset.

Example

This example demonstrates how to implement a simple website hit counter:

// Import necessary Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class SiteHitCounter implements Filter{

  private int hitCount; 

  public void  init(FilterConfig config) 
                    throws ServletException{
     // Reset the hit counter
     hitCount = 0;
  }

  public void  doFilter(ServletRequest request, 
              ServletResponse response,
              FilterChain chain) 
              throws java.io.IOException, ServletException {

      // Increment the counter by 1
      hitCount++;

      // Print the counter
      System.out.println("Website Hit Count: "+ hitCount );

      // Pass the request back down the filter chain
      chain.doFilter(request,response);
  }
  public void destroy() 
  { 
      // This step is optional, but if needed, you can write the hitCount value to a database
  } 
}

Now, let's compile the above Servlet and create the following entry in the web.xml file:

....
<filter>
   <filter-name>SiteHitCounter</filter-name>
   <filter-class>SiteHitCounter</filter-class>
</filter>

<filter-mapping>
   <filter-name>SiteHitCounter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

....

Now, access any page of the website, such as http://localhost:8080/. This will increment the counter value by 1 each time any page is hit, and it will display the following message in the log:

Website Hit Count: 1
Website Hit Count: 2
Website Hit Count: 3
Website Hit Count: 4
Website Hit Count: 5
..................
❮ Servlet Handling Date Servlet Debugging ❯