Servlets 简明教程
Servlets - Hits Counter
Hit Counter for a Web Page
很多情况下,您会希望了解网站特定页面上的点击总数。使用 servlet 计算这些点击数非常简单,因为 servlet 的生命周期由运行其的容器来控制。
Many times you would be interested in knowing total number of hits on a particular page of your website. It is very simple to count these hits using a servlet because the life cycle of a servlet is controlled by the container in which it runs.
以下是实现基于 Servlet 生命周期计数点击数的简单方法:
Following are the steps to be taken to implement a simple page hit counter which is based on Servlet Life Cycle −
-
Initialize a global variable in init() method.
-
Increase global variable every time either doGet() or doPost() method is called.
-
If required, you can use a database table to store the value of global variable in destroy() method. This value can be read inside init() method when servlet would be initialized next time. This step is optional.
-
If you want to count only unique page hits with-in a session then you can use isNew() method to check if same page already have been hit with-in that session. This step is optional.
-
You can display value of the global counter to show total number of hits on your web site. This step is also optional.
这里我假设 Web 容器不会重新启动。如果重新启动或 servlet 被销毁,则点击计数器将重置。
Here I’m assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.
Example
本示例演示如何实现简单的页面访问计数器 -
This example shows how to implement a simple page hit 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() {
// Reset hit counter.
hitCount = 0;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// This method executes whenever the servlet is hit
// increment hitCount
hitCount++;
PrintWriter out = response.getWriter();
String title = "Total Number of Hits";
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() {
// This is optional step but if you like you
// can write hitCount value in your database.
}
}
现在我们编译上述 servlet 并在 web.xml 中创建以下条目:
Now let us compile above servlet and create following entries in web.xml
<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>
....
现在使用 URL [role="bare"] [role="bare"]http://localhost:8080/PageHitCounter 调用此 servlet。每次刷新此页面,计数器都会增加 1,并且会显示以下结果 -
Now call this servlet using URL [role="bare"]http://localhost:8080/PageHitCounter. This would increase counter by one every time this page gets refreshed and it would display following result −
Total Number of Hits
6
Hit Counter for a Website:
许多时候您会希望了解整个网站上的访问总数。这在 Servlet 中也很简单,我们可以使用过滤器来实现此目的。
Many times you would be interested in knowing total number of hits on your whole website. This is also very simple in Servlet and we can achieve this using filters.
以下是实现基于过滤器生命周期的简单网站访问计数器的步骤 -
Following are the steps to be taken to implement a simple website hit counter which is based on Filter Life Cycle −
-
Initialize a global variable in init() method of a filter.
-
Increase global variable every time doFilter method is called.
-
If required, you can use a database table to store the value of global variable in destroy() method of filter. This value can be read inside init() method when filter would be initialized next time. This step is optional.
这里我假设 Web 容器不会重新启动。如果重新启动或 servlet 被销毁,则点击计数器将重置。
Here I’m assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.
Example
本示例演示如何实现简单的网站访问计数器 -
This example shows how to implement a simple website hit counter −
// Import required 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 hit counter.
hitCount = 0;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws java.io.IOException, ServletException {
// increase counter by one
hitCount++;
// Print the counter.
System.out.println("Site visits count :"+ hitCount );
// Pass request back down the filter chain
chain.doFilter(request,response);
}
public void destroy() {
// This is optional step but if you like you
// can write hitCount value in your database.
}
}
现在让我们编译上述 servlet,并在 web.xml 中创建以下项
Now let us compile the above servlet and create the following entries in web.xml
....
<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>
....
现在调用任何 URL(如 URL [role="bare"] [role="bare"]http://localhost:8080/ )。每次任何页面被访问时,计数器就会增加 1,并且会在日志中显示以下消息 -
Now call any URL like URL [role="bare"]http://localhost:8080/. This would increase counter by one every time any page gets a hit and it would display following message in the log −
Site visits count : 1
Site visits count : 2
Site visits count : 3
Site visits count : 4
Site visits count : 5
..................