Pr.Pg Next Pg

Hit Counter tutorials

  • If you are a web master of any web site than there will be a situation you want to know how many visitors have visited your web site and also how many time a single visitor have visited your site and web page.

  • It is very simple to count these hits using JSP.

  • To implement a hit counter in your web site you can make use of Application Implicit object and associated methods getAttribute() and setAttribute().

  • The Application object is available in a JSP page and the Application object is created at JSP page initialization. It is destroyed when jspDestroy() method is called at the end of JSP page execution. The following methods are used to implement hit counter. These methods are attached with you “Application” object.

setAttribute()

getAttribute()

  • To set an attribute at application level, following code is used:

application.setAttribute(String key, Object value);

  • The above setAttribute() method can be used to set the hit counter value and it is also used to reset the counter. 

  • To read the current value of page hit count use the following code:

application.getAttribute(String key);

 

 

JSP program to demonstrate hit counter to count the number of page hit

Sam Sir

<%-- Program name Hitcounter.jsp --%>

<%-- JSP program to demonstrate hit counter to count the number of page hit --%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

 

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Hit Count</title>

</head>

<body>

<h1>JSP page Counter</h1>

<%

Integer applicationCount = (Integer)application.getAttribute("applicationCount");

if (applicationCount == null)

{

applicationCount = new Integer(1);

} else

{

applicationCount= new Integer(applicationCount.intValue() + 1);

}

application.setAttribute("applicationCount", applicationCount);

%>

<br>

Visitors to this page so far <%=applicationCount%>

</body>

</html>

Output

Hit Counter in JSP

 

Note : If the server get restart then you will lost the hit count, the counter applicationCount will be reset to 0 to avoid this situation you can store your counter value in side database table.

Pr.Pg border                                              Next Pg