Sometimes we need to know the number of times a certain page has been visited. In this case, we need to add a page counter to the page. The statistics of page visits are usually accumulated when the user loads the page for the first time.
To implement a counter, you can use the application implicit object and related methods getAttribute() and setAttribute().
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 your app:
application.setAttribute(String Key, Object Value);You can use the above method to set a counter variable and update the variable's value. The method to read 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 that the new value is displayed on the page the next time the user accesses it.
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 import="java.io.*,java.util.*" %><html><head><title>Application object in JSP</title></head><body><% Integer hitsCount = (Integer)application.getAttribute("hitCounter"); if( hitsCount ==null || hitsCount == 0 ){ /* First visit*/ out.println("Welcome to my website!"); hitsCount = 1; }else{ /* Return access value*/ out.println("Welcome back to my website!"); hitsCount += 1; } application.setAttribute("hitCounter", hitsCount); %><center>< p>Total number of visits: <%= hitsCount%></p></center></body></html>
Now we place the above code on the main.jsp file and access the http://localhost:8080/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:
Welcome back to my website!Total number of visits: 12Using the above method, after the web server is restarted, the counter will be reset to 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. Write the statistical data to the data table.
On each access we read the hitcount field in the table.
Let hitcount increase by 1 each time you 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.