Easy Tutorial
❮ Jsp Expression Language Jsp Cookies ❯

JSPPage View Counter

Sometimes we need to know how many times a page has been visited, and in such cases, we need to add a page counter to the page. The page view count is typically incremented when the user first loads the page.

To implement a counter, you can use the application implicit object and its related methods getAttribute() and setAttribute().

This object represents the entire lifecycle of the JSP page. It is created when the JSP page is initialized and deleted when the JSP page calls jspDestroy().

Here is the syntax for creating a variable in the application:

application.setAttribute(String Key, Object Value);

You can use the above method to set a counter variable and update its value. The method to read the variable is as follows:

application.getAttribute(String Key);

Each time the page is accessed, you can read the current value of the counter, increment it by 1, and then reset it, so the next user will see the updated value on the page.


Example Demonstration

This example will show how to use JSP to count the total number of visits to a specific page. If you want to count the total page hits for your website, you must place this code on all JSP pages.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Page View Counter</title>
</head>
<body>
<%
    Integer hitsCount = 
      (Integer)application.getAttribute("hitCounter");
    if( hitsCount ==null || hitsCount == 0 ){
       /* First visit */
       out.println("Welcome to tutorialpro.org!");
       hitsCount = 1;
    }else{
       /* Return visit */
       out.println("Welcome back to tutorialpro.org!");
       hitsCount += 1;
    }
    application.setAttribute("hitCounter", hitsCount);
%>

<p>Page views: <%= hitsCount%></p>

</body>
</html>

Now, place the above code in the main.jsp file and access http://localhost:8080/testjsp/main.jsp. You will see a counter on the page that increments by 1 each time you refresh the page.


Resetting the Counter

Using the above method, the counter will reset to 0 after the web server restarts, meaning the previously retained data will be lost. You can solve this issue in the following ways:

❮ Jsp Expression Language Jsp Cookies ❯