很多時候,您可能有興趣知道網(wǎng)站的某個特定頁面上的總點擊量。使用 Servlet 來計算這些點擊量是非常簡單的,因為一個 Servlet 的生命周期是由它運行所在的容器控制的。
以下是實現(xiàn)一個簡單的基于 Servlet 生命周期的網(wǎng)頁點擊計數(shù)器需要采取的步驟:
在這里,我們假設 Web 容器將無法重新啟動。如果是重新啟動或 Servlet 被銷毀,計數(shù)器將被重置。
本實例演示了如何實現(xiàn)一個簡單的網(wǎng)頁點擊計數(shù)器:
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()
{
// 重置點擊計數(shù)器
hitCount = 0;
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 設置響應內容類型
response.setContentType("text/html");
// 該方法在 Servlet 被點擊時執(zhí)行
// 增加 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 的值寫入到數(shù)據(jù)庫
}
}
現(xiàn)在讓我們來編譯上面的 Servlet,并在 web.xml 文件中創(chuàng)建以下條目:
....
<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>
....
現(xiàn)在通過訪問 URL http://localhost:8080/PageHitCounter 來調用這個 Servlet。這將會在每次頁面刷新時,把計數(shù)器的值增加 1,結果如下所示:
總點擊量6 |
很多時候,您可能有興趣知道整個網(wǎng)站的總點擊量。在 Servlet 中,這也是非常簡單的,我們可以使用過濾器做到這一點。
以下是實現(xiàn)一個簡單的基于過濾器生命周期的網(wǎng)站點擊計數(shù)器需要采取的步驟:
在這里,我們假設 Web 容器將無法重新啟動。如果是重新啟動或 Servlet 被銷毀,點擊計數(shù)器將被重置。
本實例演示了如何實現(xiàn)一個簡單的網(wǎng)站點擊計數(shù)器:
// 導入必需的 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{
// 重置點擊計數(shù)器
hitCount = 0;
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException {
// 把計數(shù)器的值增加 1
hitCount++;
// 輸出計數(shù)器
System.out.println("網(wǎng)站訪問統(tǒng)計:"+ hitCount );
// 把請求傳回到過濾器鏈
chain.doFilter(request,response);
}
public void destroy()
{
// 這一步是可選的,但是如果需要,您可以把 hitCount 的值寫入到數(shù)據(jù)庫
}
}
現(xiàn)在讓我們來編譯上面的 Servlet,并在 web.xml 文件中創(chuàng)建以下條目:
....
<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>
....
現(xiàn)在訪問網(wǎng)站的任意頁面,比如 http://localhost:8080/。這將會在每次任意頁面被點擊時,把計數(shù)器的值增加 1,它會在日志中顯示以下消息:
網(wǎng)站訪問統(tǒng)計: 1
網(wǎng)站訪問統(tǒng)計: 2
網(wǎng)站訪問統(tǒng)計: 3
網(wǎng)站訪問統(tǒng)計: 4
網(wǎng)站訪問統(tǒng)計: 5
..................
更多建議: