Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet taps the counter


May 15, 2021 Servlet


Table of contents


The servlet clicks on the counter

The page clicks on the counter

Many times, you may be interested in knowing the total number of clicks on a particular page of your site. Using a servlet to calculate these clicks is very simple because the life cycle of a servlet is controlled by the container in which it runs.

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

  • Initialize a global variable in the init() method.
  • Each time the doGet() or doPost() method is called, the global variable is added.
  • If you want, you can use a database table to store the values of global variables in destroy(). T he next time the servlet is initialized, the value can be read within the init() method. This step is optional.
  • If you only want to count one page click for a session, use the isNew() method to check that the session has clicked on the same page. This step is optional.
  • You can show the total number of clicks on a page on your site by displaying the value of the global counter. This step is optional.

Here, we assume that the Web container will not restart. If the restart or servlet is destroyed, the counter is reset.

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

import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PageHitCounter extends HttpServlet{
    
  private int hitCount; 
               
  public void init() 
  { 
     // 重置点击计数器
     hitCount = 0;
  } 

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置响应内容类型
      response.setContentType("text/html");
      // 该方法在 Servlet 被点击时执行 
      // 增加 hitCount 
      hitCount++; 
      PrintWriter out = response.getWriter();
      String title = "总点击量";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +       "transitional//en\">\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() 
  { 
      // 这一步是可选的,但是如果需要,您可以把 hitCount 的值写入到数据库
  } 
} 

Now let's compile the servlet above and create the following entry .xml the web server file:

....
 <servlet>
     <servlet-name>PageHitCounter</servlet-name>
     <servlet-class>PageHitCounter</servlet-class>
 </servlet>

 <servlet-mapping>
     <servlet-name>PageHitCounter</servlet-name>
     <url-pattern>/PageHitCounter</url-pattern>
 </servlet-mapping>
....

The servlet is now http://localhost:8080/PageHitCounter by accessing the URL. This increases the value of the counter by 1 each time the page is refreshed, and the result is as follows:

Total clicks

6


Website click counter

Many times, you may be interested in knowing the total number of hits across your site. In Servlet, it's also very simple, and we can do that with filters.

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

  • Initialize a global variable in the filter's init() method.
  • Each time the doFilter method is called, the global variable is added.
  • If necessary, you can use a database table to store the value of the global variable in the filter destroy(). T he next time the filter is initialized, the value can be read within the init() method. This step is optional.

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

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

// 导入必需的 java 库
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{
     // 重置点击计数器
     hitCount = 0;
  }

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

      // 把计数器的值增加 1
      hitCount++;

      // 输出计数器
      System.out.println("网站访问统计:"+ hitCount );

      // 把请求传回到过滤器链
      chain.doFilter(request,response);
  }
  public void destroy() 
  { 
      // 这一步是可选的,但是如果需要,您可以把 hitCount 的值写入到数据库
  } 
} 

Now let's compile the servlet above and create the following entry .xml the web server 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 increases the value of the counter by 1 each time any page is clicked, and it displays the following message in the log:

网站访问统计: 1
网站访问统计: 2
网站访问统计: 3
网站访问统计: 4
网站访问统计: 5
..................