In the Web site, often need to count how many people visited this site, statistics should be based on whether it is a new answer to determine whether it is a new access to the site users. The Application object can save the number of visitors.
About application objects: The Application object is used to share data between multiple programs or multiple users, and the user uses the same Application object. This is different from the session. Once the server is started, The Application object is automatically created and saved until the server shuts down, and the Application object disappears automatically. The following is a Web site counter using the Application object, the code is as follows:
1 <%@ Page Language="Java"Import="java.util.*"pageencoding="UTF-8"%>2 <!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en">3 <HTML>4 <Body>5 <%!6 synchronized void count () {//Use the Sychronized keyword to serialize the function,7 //Make sure that there is no conflict when two users are accessing the page at the same time and modifying the count value.8 ServletContext Application=( (HttpServlet) (this)). Getservletcontext ();9 IntegerCount= (Integer) Application.getattribute ("Count");Ten One if(Count==NULL){ A Count= New Integer(1); - Application.setattribute ("Count", count); - }Else{ the Count= New Integer(Count.intvalue ()+1); - Application.setattribute ("Count", count); - } - } + %> - + <% A if(Session.isnew ()) {//determine if it is a new reply. at count (); - Out.println ("you are the first"+Application.getattribute ("Count")+"visit this website"); - } - %> - </Body> - </HTML>