Hit Counter in JSP

Hit Counter Application in JSP

In this article, we will learn how to develop Hit Counter Application in JSP. Please read our previous article where we develop a Page Redirection Application in JSP.

In this example, we will let the user know about the number of visits on a particular web page. We are creating an index.jsp page where the user will first land as a home page. Then we will implement hit counter using getAttribute() and setAttribute() methods. We are using setAttribute() to set a hit counter variable and to reset the same and getAttribute() to read the current value of the hit counter, every time a user accesses that particular web page.

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*,java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <%
 Integer hitsCount = (Integer) application.getAttribute("hitCounter");
 if (hitsCount == null || hitsCount == 0) {
  /* First visit */
  out.println("Welcome to my website!");
  hitsCount = 1;
 } else {
  /* return visit */
  out.println("Welcome back to my website!");
  hitsCount += 1;
 }
 application.setAttribute("hitCounter", hitsCount);
 %>

 <p>
  Total number of visits:
  <%=hitsCount%></p>
</body>
</html>
Output

Run your index.jsp to get the following output:

Hit Counter Application in JSP

Now refresh the page, you will get the following output:

Hits Counter Application in JSP

Here, you can see the number of visits increased by 1, likewise, the number of times you will visit the page the counter will increase by1.

In the next article, I am going to discuss How to develop Auto Page Refresh Application in JSP. Here, in this article, we develop Hits Counter Application in JSP and I hope you enjoy this Hits Counter Application in JSP article.

Leave a Reply

Your email address will not be published.