Servlet click counter


Release date:2023-11-15 Update date:2023-12-15 Editor:admin View counts:292

Label:

Servlet click counter

Page click counter

In many cases, you may be interested to know the total number of clicks on aparticular page of the site. Using Servlet to calculate these clicks is very simple, because the life cycle of an Servlet is controlled by the container in which it runs.

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

  • In init() initialize a global variable in the.

  • Each call doGet() or doPost() method, the global variable is added.

  • If desired, you can use a database table to store the values of global variables in the destroy() . The next time you initialize Servlet, this value can be found in the init() method is read within the. This step is optional.

  • If you only want to count one page click for a session session, use the isNew() method to check whether the session session has clicked on the same page. This step is optional.

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

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

Example

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

package com.runoob.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 click counter
        hitCount = 0;
    }

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

        response.setContentType("text/html;charset=UTF-8");
        // add 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" +
            "<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 necessary, you can write the value of hitCount 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.runoob.test.PageHitCounter</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PageHitCounter</servlet-name>
    <url-pattern>/TomcatTest/PageHitCounter</url-pattern>
  </servlet-mapping>
</web-app>

Now call this Servlet by accessing http://localhost:8080/TomcatTest/PageHitCounter. This will increase the value of the counter by 1 each time the page is refreshed, and the result isas follows:

Total clicks
6

Website click counter

In many cases, you may be interested to know the total number of hits on theentire site. In Servlet, this is also very simple, and we can do this usingfilters.

Here are the steps you need to take to implement a simple website click counter based on the filter life cycle:

  • In the filter init() initialize a global variable in the.

  • Each call doFilter method, the global variable is added.

  • If necessary, you can use the filter’s destroy() use a database table to store the values of global variables in the. The next time the filter is initialized, this value can be found in the init() method is read, thisstep is optional.

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

Example

This example demonstrates how to implement a simple website click 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 click counter
     hitCount = 0;
  }

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

      // Increase the value of the counter by 1
      hitCount++;

      // Output counter
      System.out.println("Website access statistics:"+ hitCount );

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

Now let’s compile the Servlet above, and in the web.xml create the following entries in the 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 visit any page of the site, such as http://localhost:8080/. This will increase the counter by 1 each time any page is clicked, and it will displaythe following message in the log:

 Website visit statistics: 1
 Website visit statistics: 2
 Website visit statistics: 3
 Website visit statistics: 4
 Website visit statistics: 5
..................

Powered by TorCMS (https://github.com/bukun/TorCMS).