May 12, 2021 JSP
Sometimes we need to know how many times a page has been visited, and then we need to add a page statisticstor to the page, which typically adds up to the number of visits to the page when the user first loads it.
To implement a counter, you can implement it using application implicit objects 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().
Here's the syntax for creating variables in your app:
application.setAttribute(String Key, Object Value);
You can use the above methods to set a counter variable and update the value of that variable. Here's how to read the variable:
application.getAttribute(String Key);
Each time the page is accessed, you can read the current value of the counter, increment 1, and then reset it to display the new value on the page when the next user visits.
This example shows how to use JSP to calculate the total number of page visits. If you want to count the total number of clicks on the pages your site uses, you must place the code on all JSP pages.
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation object in JSP</title>
</head>
<body>
<%
Integer hitsCount = (Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ){
/* 第一次访问 */
out.println("Welcome to my website!");
hitsCount = 1;
}else{
/* 返回访问值 */
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 let's place the code above on .jsp the main file and access the http://localhost:8080/main.jsp file. Y ou'll see that the page generates a counter that changes each time we refresh the page (an increase of 1 per refresh). Y ou can also access it through a different browser, and the counter increases by 1 after each visit. Here's what it looks like:
Welcome back to my website! Total number of visits: 12
Using the above method, after the web server restarts, the counter is reset to 0, i.e. the data retained earlier disappears, and you can solve the problem in a few ways: