To count number of visitors at any page in JSP. We need to use of application Implicit object and methods getAttribute() and setAttribute().
This object is a representation of the JSP page through its complete lifecycle. This object is created when the JSP page is initialized and it will be removed when the JSP page is removed by the jspDestroy() method.
How to set a variable at the application level :
application.setAttribute(String Key, Object Value);
How to read the variable set by the previous method :
When a user hit the application. You can read the current value by application.getAttribute(String Key); and Increment that value by one like a counter and again set the value for future use.
Below is the complete example of the task:
How to count number of visitors for website in jsp.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
Integer counter = (Integer)application.getAttribute("counter");
if (counter ==null || counter == 0)
out.println("Welcome to my website!");
counter = 1;
out.println("Welcome back to my website!");
out.println("Total Number of visitors : "+counter);