JSP hits Statistics

Sometimes we need to know the number of times a page has been accessed. In this case, we need to add a page statistic on the page. The statistics of the page access generally accumulate the number of accesses of the page when the user first loads.

To implement a counter, you can do so using the application implicit object and related methods getAttribute() and setAttribute().

This object represents the entire life cycle of a JSP page. This object is created when the JSP page is initialized, and is deleted when the JSP page calls jspDestroy().

The following is the syntax for creating variables in your app:

application.setAttribute(String Key< /span>, Object /span>Value);

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

application.getAttribute(String Key< /span>);

Each time the page is accessed, you can read the current value of the counter, increment it by 1, then reset it, and display the new value on the page when the next user accesses it.

Instance Demo

This example shows how to use JSP to calculate the total number of people accessing a particular page. If you want to calculate the total number of hits on your site's pages, then you must put that code on all JSP pages.

<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@ page import="java.io.*,java.util.*" %>
<title>hits statistics</title>
    Integer hitsCount = 
    if( hitsCount ==null || hitsCount == 0 ){
       /* First visit */
       out.println("Welcome to the welookups tutorial!");
       hitsCount = 1;
       /* Return access value */
       out.println("Welcome to visit the welookups tutorial again!");
       hitsCount += 1;
    application.setAttribute("hitCounter", hitsCount);

<p>Page visits are: <%= hitsCount%></p>


Now we put the above code in the main.jsp file and access the http://localhost:8080/testjsp/main.jsp file. You will see that the page will generate a counter, and the counter will change every time we refresh the page (one increment per update).

You can also access it through different browsers, and the counter will increment by 1 after each visit. As follows: