Latest web development tutorials

Hit Counter Servlet

Page hit counter

Many times, you might be interested to know the total amount of clicks on a particular page of your site. Servlet use to calculate these clicks are very simple, because the life cycle of a Servlet container by its control is running.

The following is based on the realization of a simple Servlet life cycle page hit counter steps to be taken:

  • Initialize a global variable in the init () method.
  • Each call doGet () or doPost () method, we have increased global variables.
  • () If desired, you can use a database table to store the value of the global variable destroy. At the next initialization Servlet, this value can be read in the init () method. This step is optional.
  • If you want a session once the session count page hits, use isNew () method to check whether the session conversation has been clicked on the same page. This step is optional.
  • You can display the global value of the counter, to show the total traffic pages on your site. This step is optional.

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

Examples

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

package com.w3big.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() 
	{ 
		// 重置点击计数器
		hitCount = 0;
	} 
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		// 增加 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() 
	{ 
		// 这一步是可选的,但是如果需要,您可以把 hitCount 的值写入到数据库
	} 

}

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.w3big.test.PageHitCounter</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PageHitCounter</servlet-name>
    <url-pattern>/TomcatTest/PageHitCounter</url-pattern>
  </servlet-mapping>
</web-app>

Now by visiting http: to call the Servlet 8080 / TomcatTest / PageHitCounter: // localhost. This will refresh the page every time, to increase the value of the counter 1, the result is as follows:

Total number of hits

6


Website Hit Counter

Many times, you might be interested to know the total traffic of the entire site. In Servlet, this is very simple, we can use the filter to do this.

The following is to implement a simple filter-based Life Cycle website hit counter steps to be taken:

  • () Method to initialize a global variable filter init.
  • Each call doFilter methods, have increased global variables.
  • If desired, you can use a database table () in the filter destroy global variable to store the value. Next initialization of the filter, the value can be read in the init () method, this step is optional.

Here, we assume that the Web container can not be restarted. If you restart or Servlet is being destroyed, the hit counter will be reset.

Examples

This example demonstrates how to implement a simple site hit 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 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 your site, such as http: // localhost: 8080 /. This will in any page each time it is clicked, the increase in value of the counter 1, it will display the following message in the log:

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