JSP click statistics
Sometimes we need to know the number of times a certain page has been visited. In this case, we need to add a page statistic to the page. The statistics of page visits are generally accumulated when the user loads the page for the first time. Count on.
To implement a counter, you can use the application implicit object and related methods getAttribute() and setAttribute() to achieve it.
This object represents the entire life cycle of the JSP page. This object is created when the JSP page is initialized and deleted when the JSP page calls jspDestroy().
The following is the syntax for creating variables in the application:
application.setAttribute(String Key, Object Value);
You can use the above method to set a counter variable and update the value of the variable. The method of reading this variable is as follows:
application.getAttribute(String Key);
Every time the page is accessed, you can read the current value of the counter, increment it by 1, and then reset it, and the new value will be used when the next user accesses displayed on the page.
Example Demonstration
This example will introduce how to use JSP to calculate the total number of people visiting a specific page. If you want to calculate the total number of clicks on the pages used on your website, then 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.*" %> <html> <html> <head> <title>访问量统计</title> </head> <body> <% Integer hitsCount = (Integer)application.getAttribute("hitCounter"); if( hitsCount ==null || hitsCount == 0 ){ /* 第一次访问 */ out.println("欢迎访问php中文网!"); hitsCount = 1; }else{ /* 返回访问值 */ out.println("欢迎再次访问php中文网!"); hitsCount += 1; } application.setAttribute("hitCounter", hitsCount); %> <p>页面访问量为: <%= hitsCount%></p> </body> </html>
Now we place the above code on 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 every time we refresh the page, the counter will change (incremented by 1 for each refresh).
You can also access it through different browsers, and the counter will increase by 1 after each visit. As shown below:Reset counter
Using the above method, the counter will be reset after the web server is restarted. is 0, that is, the previously retained data will disappear. You can use the following methods to solve this problem:
Define a data table count in the database for counting web page visits. The field is hitcount, the default value of hitcount is 0, and the statistical data is written to the data table.
We read the hitcount field in the table on each visit.
Increase hitcount by 1 for each visit.
Display the new hitcount value on the page as the number of page views.
If you need to count the number of visits to each page, you can use the above logic to add the code to all pages.