Skip to main content

how to count the page views by using JSP

Tracking Page Views in Java Web Applications Using JSP Scopes

JSP Page View Tracking Architecture JSP Page View Tracking Architecture 1 HTTP Request Client sends request to JSP page or Servlet in container. 2 State Analysis Evaluate stateless HTTP and choose correct Servlet scope. 3 Application Scope Access global ServletContext via implicit application object. 4 Increment Counter Safely update and store aggregate hit count metrics.
Figure: JSP Page View Tracking Architecture

Counting page views is a foundational requirement in web applications. Whether you need to monitor traffic bottlenecks, audit navigation patterns, or display live counters on an enterprise dashboard, managing state across multiple pages is necessary. In classical Java EE architectures, JavaServer Pages (JSP) and Servlets handle these state requirements using built-in scopes.

Pick a language, then press Listen.

This tutorial covers implementing a robust page view tracking system using the JSP application scope. You will build a multi-page application that tracks both individual page hits and total application-wide requests. While modern architectures often lean toward modern front-end tracking or microservices—similar to when you are Dockerizing a Spring Boot Application with MySQL—understanding Servlet context scopes remains essential for maintaining legacy systems and grasping the fundamentals of Java web state management.

The Problem: State Management Across HTTP Requests

HTTP is a stateless protocol. Every time a client requests a JSP or Servlet, the server processes the request and returns a response, completely forgetting that the same client previously requested another page. To accumulate metrics like "total views across the entire application," state must be stored somewhere persistent for the duration of the web application's lifecycle.

Java web containers provide four standard scopes for data sharing:

  • Page Scope: Data is accessible only within the single JSP page where it was created.
  • Request Scope: Data is available for the duration of a single HTTP request-response cycle.
  • Session Scope: Data persists across multiple requests from a specific user session.
  • Application Scope: Data is shared globally across all users, sessions, and servlets within the same web application context.

Because page view tracking requires aggregating hits from all visitors, the Application Scope (represented by javax.servlet.ServletContext in the servlet API and accessible via the implicit JSP object application) is the correct choice.

Prerequisites and Environment Setup

To follow this implementation, ensure your local development environment includes:

  • An IDE supporting Java EE/Jakarta EE web development (such as Eclipse IDE for Enterprise Java Developers).
  • A Servlet container compliant with JSP 2.3+ (such as Apache Tomcat 9 or 10).
  • Java Development Kit (JDK) 8 or higher (if you are exploring modern language constructs on newer runtimes, consider reviewing Java 17 Records and Pattern Matching with Examples for backend data transfer objects).

Step-by-Step Implementation

Create a new Dynamic Web Project in your IDE named PageCounter. Within your WebContent (or src/main/webapp) directory, create three JSP files: firstFile.jsp, secondFile.jsp, and thirdFile.jsp.

1. Implementing the First Page (firstFile.jsp)

The first file initializes the application-scoped variables if they do not already exist. It increments both the global counter and the specific counter for page one.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    // 1. Retrieve or initialize the total application-wide counter
    Integer allPagesCount = (Integer) application.getAttribute("allPagesCount");
    if (allPagesCount == null) {
        allPagesCount = 1;
    } else {
        allPagesCount += 1;
    }

    // 2. Retrieve or initialize the specific counter for the first page
    Integer firstPageCounter = (Integer) application.getAttribute("firstPageCounter");
    if (firstPageCounter == null) {
        out.println("<p>Hello, welcome to the first page for the very first time!</p>");
        firstPageCounter = 1;
    } else {
        out.println("<p>Welcome back to the first page!</p>");
        firstPageCounter += 1;
    }

    // 3. Save the updated counts back to the application scope
    application.setAttribute("firstPageCounter", firstPageCounter);
    application.setAttribute("allPagesCount", allPagesCount);
%>
<!DOCTYPE html>
<html>
<head>
    <title>First Page - Page Counter</title>
</head>
<body>
    <div style="text-align: center; margin-top: 50px;">
        <p style="color: maroon;"><b>First Page Total Visits:</b> <%= firstPageCounter %></p>
        <p style="color: blue;"><b>All Pages Total Visits:</b> <%= allPagesCount %></p>
    </div>
    
    <div style="margin-top: 30px; text-align: center;">
        <a href="secondFile.jsp">Navigate to Second Page</a> | 
        <a href="thirdFile.jsp">Navigate to Third Page</a>
    </div>
</body>
</html>

2. Implementing the Second Page (secondFile.jsp)

Create the second file following the same logic, targeting its own unique attribute key secondPageCounter while sharing the global allPagesCount.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    Integer allPagesCount = (Integer) application.getAttribute("allPagesCount");
    if (allPagesCount == null) {
        allPagesCount = 1;
    } else {
        allPagesCount += 1;
    }

    Integer secondPageCounter = (Integer) application.getAttribute("secondPageCounter");
    if (secondPageCounter == null) {
        out.println("<p>Hello, welcome to the second page for the very first time!</p>");
        secondPageCounter = 1;
    } else {
        out.println("<p>Welcome back to the second page!</p>");
        secondPageCounter += 1;
    }

    application.setAttribute("secondPageCounter", secondPageCounter);
    application.setAttribute("allPagesCount", allPagesCount);
%>
<!DOCTYPE html>
<html>
<head>
    <title>Second Page - Page Counter</title>
</head>
<body>
    <div style="text-align: center; margin-top: 50px;">
        <p style="color: maroon;"><b>Second Page Total Visits:</b> <%= secondPageCounter %></p>
        <p style="color: blue;"><b>All Pages Total Visits:</b> <%= allPagesCount %></p>
    </div>
    
    <div style="margin-top: 30px; text-align: center;">
        <a href="firstFile.jsp">Navigate to First Page</a> | 
        <a href="thirdFile.jsp">Navigate to Third Page</a>
    </div>
</body>
</html>

3. Implementing the Third Page (thirdFile.jsp)

Complete the navigation loop by setting up thirdFile.jsp using the exact same architectural pattern with a thirdPageCounter key.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    Integer allPagesCount = (Integer) application.getAttribute("allPagesCount");
    if (allPagesCount == null) {
        allPagesCount = 1;
    } else {
        allPagesCount += 1;
    }

    Integer thirdPageCounter = (Integer) application.getAttribute("thirdPageCounter");
    if (thirdPageCounter == null) {
        out.println("<p>Hello, welcome to the third page for the very first time!</p>");
        thirdPageCounter = 1;
    } else {
        out.println("<p>Welcome back to the third page!</p>");
        thirdPageCounter += 1;
    }

    application.setAttribute("thirdPageCounter", thirdPageCounter);
    application.setAttribute("allPagesCount", allPagesCount);
%>
<!DOCTYPE html>
<html>
<head>
    <title>Third Page - Page Counter</title>
</head>
<body>
    <div style="text-align: center; margin-top: 50px;">
        <p style="color: maroon;"><b>Third Page Total Visits:</b> <%= thirdPageCounter %></p>
        <p style="color: blue;"><b>All Pages Total Visits:</b> <%= allPagesCount %></p>
    </div>
    
    <div style="margin-top: 30px; text-align: center;">
        <a href="firstFile.jsp">Navigate to First Page</a> | 
        <a href="secondFile.jsp">Navigate to Second Page</a>
    </div>
</body>
</html>

Comparison of JSP Scopes for Tracking Data

Choosing the appropriate scope dictates whether your counters track individual user actions, browsing sessions, or global traffic. The table below outlines the operational differences.

Scope Object Java Interface Lifetime Duration Visibility / Accessibility Use Case for Counters
pageContext javax.servlet.jsp.PageContext Single JSP execution Current page only Unsuitable for page view tracking.
request javax.servlet.http.HttpServletRequest Single HTTP request-response cycle Current request and dispatched components Tracks single-page hits per request, but resets on redirects.
session javax.servlet.http.HttpSession Browser session duration (until timeout/close) Single user session across multiple requests Tracks how many times a specific user visited a page.
application javax.servlet.ServletContext Application startup to server shutdown Global across all users and servlets Tracks total aggregate visits across all users (Global Counter).

Real-World Edge Cases and Technical Gotchas

While the implementation above functions properly in a controlled tutorial setting, production environments introduce complexities that raw scriptlets fail to handle gracefully.

1. Concurrency and Thread Safety Issues

The application scope object is shared globally across all worker threads handling concurrent HTTP requests in the servlet container. Code patterns such as reading an integer, performing arithmetic operations (+= 1), and writing it back are not thread-safe. Under heavy concurrent load, multiple threads can read the same value simultaneously, leading to lost updates (race conditions).

Solution: Wrap counter increments inside a synchronized block using a lock object, or transition the counter logic to an enterprise bean, Servlet Filter, or use Java's atomic types like AtomicInteger stored within the servlet context.

2. Server Restarts and Persistence

Variables stored in the application scope reside entirely in server memory. When the application server restarts, crashes, or performs a hot-deployment, all state vanishes, and counters reset to zero.

Solution: For persistent analytics, integrate a database backend (such as MySQL or Oracle—for enterprise database connectivity configurations, see JNDI configuration for Tomcat 9 with Oracle) to flush counts periodically or on application shutdown via a ServletContextListener.

3. Double-Counting from Page Refreshes and Bots

Every time a user hits F5 (refresh) or a web crawler indexes the page, the scriptlet executes, incrementing the counter artificially. This distorts analytics accuracy.

Solution: Implement session-based tracking flags or check HTTP request headers (like User-Agent) to filter out common web crawlers and prevent duplicate increments from page refreshes.

Troubleshooting Common Issues

  • NullPointerException on Casting: If another part of your application modifies context attributes or removes them, casting to Integer without checking for null can throw exceptions. Always validate retrieved attributes.
  • ClassCastException: Ensure you do not mix data types. If an attribute is stored as a String or a custom object elsewhere, casting it directly to Integer fails at runtime.
  • Scriptlet Maintenance Overhead: Embedding complex Java logic directly inside JSP files violates the Model-View-Controller (MVC) design pattern. For production environments, migrate this logic into a dedicated Servlet or Controller, and use JSTL or Expression Language (EL) to display the counts safely.

Summary

Counting page views in Java web applications requires choosing the correct scope to match your tracking requirements. Utilizing the JSP application scope provides a straightforward mechanism for accumulating global statistics across all users. However, scriptlet-based implementations in production systems face thread safety, persistence, and architectural limitations. Migrating this business logic into enterprise servlets, applying atomic operations for concurrent requests, and persisting metrics to a database ensures your tracking infrastructure scales reliably under real-world traffic loads.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...