Table of contents
1.
Introduction
2.
How it works?
3.
Example for Hit Counter
4.
Online Visitors
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

JSP Hits Counter

Author Abhay Trivedi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Have you ever seen the count of online users and total visitors to a website? Well, that is possible by using JSP Hits Counter. JSP or Java Server Pages is a Web-based server-side technology used for creating web applications & dynamic web content. A JSP hits counter tells us about the number of visitors on a particular website page. Usually, we attach a hit counter with our index.jsp page, considering users landing on the home page first.

How it works?

We will implement JSP Hit Counter using getAttribute() & setAttribute() methods. We use setAttribute() to set and reset a hit counter variable and getAttribute() to read the value of the hit counter every time a user try to accesses that particular web page.

Read the value of the hit counter like:

application.getAttribute(string_key);
You can also try this code with Online Java Compiler
Run Code

Set and reset a hit counter variable like:

application.setAttribute(string_key, value);
You can also try this code with Online Java Compiler
Run Code

Example for Hit Counter

Here is an example of the JSP Hits Counter, which shows the total number of visitors on a website.

<%@ page import = "java.io.*,java.util.*" %>

<html>
   <head>
      <title>JSP Hits Counter Example</title>
   </head>   
   
   <body>
      <%
         Integer hitsCount = (Integer) application.getAttribute("hitCounter");
         // First visit 
		 if( hitsCount == null || hitsCount == 0 ) {
            out.println("JSP Hits Counter Example");
            hitsCount = 1;
         } else {
            out.println("Welcome back!");
            hitsCount += 1;
         }
         application.setAttribute("hitCounter", hitsCount);
      %>

      <p>Total number of visitors: <%= hitsCount%></p>

   </body>
</html>

Output:

  First visit:

  After visits:

Hit Counter Resets: The counter variable will reset to zero when we restart our web server. To avoid this loss, we should store the value of our variable in a database table.

Online Visitors

To count the online visitors on a webpage, use the Java Servlet Filter that intercepts all the requests coming to the web application and increases the count by 1 for every request. 

package net.codejava;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUserListener implements HttpSessionListener {
    static final String ONLINE_USERS = "onlineVisitors";
    
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        ServletContext context = event.getSession().getServletContext();
        
        Integer onlineUsers = 0;
        
        Object onlineUsersYet = context.getAttribute(ONLINE_USERS);
        
        if(onlineUsersYet) {
            onlineUsers = (Integer) onlineUsersYet;       
        }
        
        context.setAttribute(ONLINE_USERS, ++onlineUsers);
    }
 
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        ServletContext context = event.getSession().getServletContext();
        
        Integer onlineUsers = (Integer) context.getAttribute(ONLINE_USERS);
        
        context.setAttribute(ONLINE_USERS, --onlineUsers);
    }
}
You can also try this code with Online Java Compiler
Run Code

Output:

You can also read about the JSP Architecture and Lifecycle.

Frequently Asked Questions

1. What is JSP?

JSP or Java Server Pages is a Web-based server-side technology used for creating web applications & dynamic web content. We use JSP tags to insert JAVA code into HTML pages. JSP is an advanced version of Servlet Technology that helps create dynamic and platform-independent web pages by inserting Java code in HTML/ XML pages or both. The JSP container first converts JSP into a servlet and processes the client’s request.

2. What is the difference between JSP and HTML?

JSP is a server-side technology that we use to create dynamic web applications. HyperText markup language (HTML) is used to create the structure of web pages. JSP allows placing the custom tag or third-party tag. It does not permit the placement of the custom tag or third-party tag.

3. What is JSP Hits Counter?

A JSP hits Counter tells us about the number of visitors on a particular website page. Usually, we attach a hit counter with your index.jsp page, considering people land on the home page first.

4. What is jspDestroy() method?

The jspDestroy() method is the JSP equivalent for the servlet destroy method. Use jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.

5. Is JSP secure?

JavaServer Pages or JSP and servlets make several mechanisms available to Web developers to secure their applications. Resources are protected declaratively by recognizing them in the application deployment descriptor and allocating their role.

Key Takeaways

This article teaches about JSP Hits Counter and how we use them. We saw why JSP Hits Counter could be beneficial for a developer to learn. Click here to read about Java Interview Questions.

Click here to see other related blogs on JAVA.

Recommended Readings:

Check out our Web development course and blogs on Backend Web Technologies.

If you are preparing for your DSA interviews then, Coding Ninjas Studio is a one-stop destination. This platform will help you acquire effective coding techniques and overview student interview experience in various product-based companies.

Happy Learning!

Live masterclass