English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Click Counter

Web page click counter

Many times, you may be interested in knowing the total number of clicks on a specific page on the website. It is very simple to calculate these clicks using Servlet, because the lifecycle of a Servlet is controlled by the container it runs in.

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

  • Initialize a global variable in the init() method.

  • The global variable is incremented each time the doGet() or doPost() method is called.

  • If necessary, you can use a database table to store the value of global variables in the destroy() method. This value can be read in the init() method when the Servlet is initialized next time. This step is optional.

  • If you only want to count the page click of a session once, please use the isNew() method to check if the session has clicked the same page before. This step is optional.

  • You can display the total number of page clicks on the website by showing the value of the global counter. This step is optional.

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

Online example

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

package com.w3codebox.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 the click counter
        hitCount = 0;
    } 
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        // increase hitCount 
        hitCount++; 
        PrintWriter out = response.getWriter();
        String title = "总点击量";
        String docType = "<!DOCTYPE html> \n";
        out.println(docType +
            "<html>\n" +
            "<head><title>" + title + "</title></head>\n" +
            "<body bgcolor=\"#f0f0f0\">\n" +
            "<h1 align="center">" + title + "</h1>\n" +
            "<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 the 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.w3codebox.test.PageHitCounter</servlet-class>
  </</servlet>
  <servlet-mapping>
    <servlet-name>PageHitCounter</servlet-name>
    <url-pattern>/TomcatTest/PageHitCounter</url-pattern>
  </servlet-mapping>
</web-app>

Now access http://localhost:8080/TomcatTest/PageHitCounter to call this Servlet. This will increase the counter value each time the page is refreshed 1, as shown below:

Total number of clicks

6

Website hit counter

Many times, you may be interested in knowing the total number of clicks on the entire website. In Servlet, this is also very simple, and we can achieve this with a filter.

The following steps need to be taken to implement a simple website hit counter based on the filter lifecycle:

  • Initialize a global variable in the init() method of the filter.

  • The global variable is incremented each time the doFilter method is called.

  • If necessary, you can use a database table in the destroy() method of the filter to store the value of the global variable. This value can be read in the init() method when the filter is initialized next, which is optional.

Here, we assume that the Web container will not be able to restart. If it restarts or the Servlet is destroyed, the hit counter will be reset.

Online example

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

// Import the 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 click counter
     hitCount = 0;
  }
  public void doFilter(ServletRequest request, 
              ServletResponse response,
              FilterChain chain) 
              throws java.io.IOException, ServletException {
      // Increase the counter value 1
      hitCount++;
      // Output Counter
      System.out.println("Website Access Statistics:")+ hitCount);
      // Pass the request back to the filter chain
      chain.doFilter(request,response);
  }
  public void destroy() 
  { 
      // This step is optional, but if needed, you can write the 'hitCount' value to the 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 increase the counter value every time any page is clicked 1It will display the following message in the log:

Website Access Statistics: 1
Website Access Statistics: 2
Website Access Statistics: 3
Website Access Statistics: 4
Website Access Statistics: 5
..................