Servlet Hit Counter
Page Hit Counter
Many times, you may be interested in knowing the total number of hits on a specific page of a website. Using Servlet to count these hits is very simple, because the lifecycle of a Servlet is controlled by the container in which it runs.
The following are the steps required to implement a simple Servlet lifecycle-based page hit counter:
- Initialize a global variable in the init() method.
- Increment the global variable every time the doGet() or doPost() method is called.
- If needed, you can use a database table to store the value of the global variable in destroy(). The value can be read in the init() method the next time the Servlet is initialized. This step is optional.
- If you want to count a page hit only once per session, use the isNew() method to check whether the session has already clicked the same page. This step is optional.
- You can display the total page hits on the website by showing the value of the global counter. This step is optional.
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 page hit counter:
package com.example.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 entries in the web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>PageHitCounter</servlet-name>
<servlet-class>com.example.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 visiting http://localhost:8080/TomcatTest/PageHitCounter. This will increment the counter value by 1 each time the page is refreshed, and the result is as follows:
Total Hits6 |
Website Hit Counter
Many times, you may be interested in knowing the total number of hits for the entire website. In Servlet, this is also very simple, and we can use a filter to achieve this.
The following are the steps required to implement a simple filter lifecycle-based website hit counter:
- Initialize a global variable in the filter's init() method.
- Increment the global variable every time the doFilter method is called.
- If needed, you can use a database table in the filter's destroy() to store the value of the global variable. The value can be read in the init() method the next time the filter is initialized. This step is optional.
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:
// 导入必需的 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 entries 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 visit any page of the website, for example 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:
网站访问统计: 1 网站访问统计: 2 网站访问统计: 3 网站访问统计: 4 网站访问统计: 5 ..................Other Extensions