Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Servlet Hit Counter

Servlet Hit Counter

Web Page Hit Counter

Often, you may be interested in knowing the total number of hits on a particular page of your website. Using a 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 needed to implement a simple Servlet lifecycle-based web page hit counter:

Here, we assume 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 web page hit counter:



package com.runoob.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() 

    { 

        // Reset click counter

        hitCount = 0;

    } 

    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        response.setContentType("text/html;charset=UTF-8");

        // increase hitCount

        hitCount++; 

        PrintWriter out = response.getWriter();

        String title = "Total Hits";

        String docType = " \n";

        out.println(docType +

            "\n" +

            "" + title + "\n" +

            "\n" +

            "

" + title + "

\n" +      "

" + hitCount + "

\n" +      "");     }          public void destroy()     {         // This step is optional, but if needed, you can write the hitCount value to the database     } }

Now let's compile the above Servlet and create the following entry in the web.xml file:







  

    PageHitCounter

    com.runoob.test.PageHitCounter

  

  

    PageHitCounter

    /TomcatTest/PageHitCounter

  



Now invoke this Servlet by visiting http://localhost:8080/TomcatTest/PageHitCounter. This will increment the counter by 1 each time the page is refreshed, and the result is as follows:

Total Hits

6

Website Hit Counter

Often, you may be interested in knowing the total number of hits on your entire website. In a Servlet, this is also very simple; we can use a filter to do this.

The following are the steps needed to implement a simple filter lifecycle-based website hit counter:

Here, we assume 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:



// Import necessary 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 click counter

     hitCount = 0;

  }



  public void  doFilter(ServletRequest request, 

              ServletResponse response,

              FilterChain chain) 

              throws java.io.IOException, ServletException {



      // Increment the counter value by 1

      hitCount++;



      // Output counter

      System.out.println("网站访问统计:"+ hitCount );



      // Pass the request back to the filter chain

      chain.doFilter(request,response);

  }

  public void destroy() 

  { 

      // This step is optional, but if needed, you can write the hitCount value to the database

  } 

} 

Now let's compile the above Servlet and create the following entry in the web.xml file:



....



   SiteHitCounter

   SiteHitCounter







   SiteHitCounter

   /*





....

Now visit any page of the website, such as http://localhost:8080/. This will increment the counter by 1 each time any page is hit, and it will display the following message in the log:



网站访问统计: 1

网站访问统计: 2

网站访问统计: 3

网站访问统计: 4

网站访问统计: 5

..................