HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Sometimes we need to know the number of times a page is accessed, then we need to add the page count in the page, the page access statistics generally when the user first loads accumulated on the number of visits to the page.
To implement a counter, you can use the application implicit object and related methods getAttribute () and setAttribute () to achieve.
This object represents the entire life cycle of JSP pages. This object is created when the JSP page is initialized, the object is deleted when the JSP page calls jspDestroy ().
The following variables are created in the application syntax:
application.setAttribute(String Key, Object Value);
You can use the above method to set a counter variable and update the value of the variable. Read the variable as follows:
application.getAttribute(String Key);
When each page is accessed, you can read the current value of the counter and is incremented by 1, then re-set, the next time a user accesses the new value will be displayed on the page.
This example describes how to use JSP to calculate the total number of people visited a particular page. If you want to calculate the total traffic to your site using pages, then you have all the code on the JSP page.
<%@ 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("欢迎访问本教程!"); hitsCount = 1; }else{ /* 返回访问值 */ out.println("欢迎再次访问本教程!"); hitsCount += 1; } application.setAttribute("hitCounter", hitsCount); %> <p>页面访问量为: <%= hitsCount%></p> </body> </html>
Now we will above code placed on main files, and access http: // localhost: 8080 / testjsp / main file. You will see the page will generate a counter each time we refresh the page, the counter will change (increase by 1 each refresh).
You can also access a different browser, the counter will increase after each visit 1. As follows:Using the above method, after the web server is restarted, the counter is reset to 0, that is, to retain the previous data will disappear and you can use at several ways to solve the problem: