Servlets-hits-counter

提供:Dev Guides
移動先:案内検索

サーブレット-ヒットカウンター

Webページのヒットカウンター

多くの場合、あなたはあなたのウェブサイトの特定のページでのヒットの総数を知ることに興味があるでしょう。 サーブレットのライフサイクルは、実行するコンテナによって制御されるため、サーブレットを使用してこれらのヒットをカウントするのは非常に簡単です。

以下は、サーブレットライフサイクルに基づく単純なページヒットカウンタを実装するために実行する手順です。

  • init()メソッドでグローバル変数を初期化します。
  • doGet()またはdoPost()メソッドが呼び出されるたびにグローバル変数を増やします。
  • 必要に応じて、データベーステーブルを使用して、グローバル変数の値をdestroy()メソッドに格納できます。 この値は、次回サーブレットが初期化されるときにinit()メソッド内で読み取ることができます。 この手順はオプションです。
  • セッション内で一意のページヒットのみをカウントする場合は、isNew()メソッドを使用して、そのセッション内で同じページが既にヒットしているかどうかを確認できます。 この手順はオプションです。
  • グローバルカウンタの値を表示して、Webサイトでのヒットの総数を表示できます。 このステップもオプションです。

ここでは、Webコンテナが再起動されないと想定しています。 再起動するか、サーブレットを破棄すると、ヒットカウンターはリセットされます。

この例では、単純なページヒットカウンタを実装する方法を示します-

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.
   }
}

次に、上記のサーブレットをコンパイルして、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>
....

Now call this servlet using URL http://localhost:8080/PageHitCounter. This would increase counter by one every time this page gets refreshed and it would display following result −

Webサイトのヒットの総数6ヒットカウンター:

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.

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。*;

パブリッククラスSiteHitCounterはFilter {

private int hitCount;

public void init(FilterConfig config)throws ServletException {//ヒットカウンターをリセットします。 hitCount = 0; }

public void doFilter(ServletRequestリクエスト、ServletResponseレスポンス、FilterChainチェーン)はjava.io.IOException、ServletExceptionをスローします{

//カウンターをhitCount ++で1つ増やします。

//カウンターを印刷します。 System.out.println( "Site visits count:" + hitCount);

//フィルターチェーンにリクエストを渡しますchain.doFilter(request、response); } public void destroy(){//これはオプションの手順ですが、必要に応じて//データベースにhitCount値を書き込むことができます。 }  }

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>
....

Now call any URL like URL 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 −

サイト訪問数:1サイト訪問数:2サイト訪問数:3サイト訪問数:4サイト訪問数:5
..................