Pr.Pg Next Pg

Hit Counter for a Web Site or Web Application tutorials

  • Many a times web Administrator would be interested to knowing the total number of hits on his web site.

  • This is also similar to the above scenario but we have to count hits on whole web site not on single web page.

  • This is achieved by using filters and assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will be reset.

  • Below are the steps to be taken to implement a simple website hit counter which is based on Filter Life Cycle:

    1. Initialize a class level variable in init() method of a filter.

    2. Increase class level variable every time doFilter method is called.

 

Example: Servlet program to show the website hit counter

Sam Sir

//Program name HitCountServletFilter.java

// Program to show the website hit counter

 

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class HitCountServletFilter implements Filter {

private int hitCount;

public void destroy()

{

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

hitCount++;

System.out.println("Site visits count :" + hitCount);

request.setAttribute("counter", hitCount);

chain.doFilter(request, response);

}

public void init(FilterConfig fConfig) throws ServletException {

hitCount = 0;

}

}

 

 

 


 

Example: Jsp file for getting the attribute counter from above filter

Sam Sir

<!--Program name index.jsp- ->

<!-- Jsp file for getting the attribute counter from above filter- ->

<html>

<head>

<title>Counter</title>

</head>

<body>

<h1>Web Site Hit Counter</h1>

<%=request.getAttribute("counter")%>

</body>

</html>

Output

Hit Counter in Servlets for web App or web site

Pr.Pg border                                              Next Pg