Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JSP Hit Counter

JSP Hit Counter

Sometimes we need to know how many times a page has been visited, in which case we need to add a page counter to the page. Page visit counting generally increments the page's visit count when a user first loads it.

To implement a counter, you can use the application implicit object and the 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 removed when the JSP page calls jspDestroy().

The following is the syntax for creating a variable in the application:



application.setAttribute(String Key, Object Value);

You can use the above methods to set a counter variable and update its value. The method for reading this 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 new value is displayed on the page when the next user visits.


Example Demonstration

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



<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

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







访问量统计





<%

    Integer hitsCount = 

      (Integer)application.getAttribute("hitCounter");

    if( hitsCount ==null || hitsCount == 0 ){

       /* 第一次访问 */

       out.println("欢迎访问Runoob Tutorial!");

       hitsCount = 1;

    }else{

       /* 返回访问值 */

       out.println("欢迎再次访问Runoob Tutorial!");

       hitsCount += 1;

    }

    application.setAttribute("hitCounter", hitsCount);

%>



页面访问量为: <%= hitsCount%>

Now we place the above code in the main.jsp file and accesshttp://localhost:8080/testjsp/main.jspthe file. You will see that the page generates a counter; each time we refresh the page, the counter changes (increasing by 1 with each refresh).

You can also access through different browsers; the counter increases by 1 after each visit. As shown below:


Resetting the Counter

Using the above method, after the web server restarts, the counter is reset to 0, meaning the previously retained data disappears. You can use the following approaches to solve this problem: