There are many ways to implement site counters in JSP pages, and the common practice is to use application and session objects. The Application object can be shared by all users, the session is a single-user sharing, the user from the access system to exit the system, can use the session. The idea of the website counter is: When the system creates a Session object, add 1 to the count variable saved in application
count.jsp
<%@ Pagelanguage= "Java"Import= "java.util.*"pageencoding= "Utf-8"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"><HTML> <Head> </Head> <Body> <%! Synchronizedvoid Countpeople () {ServletContext application= This.getservletcontext (); Integer Number= (Integer)Application.getattribute ("Count"); if ( number== null) { number= newInteger (1); Application.setattribute ("Count", number); } else{ Number= newInteger (Number.intvalue () + 1); Application.setattribute ("Count", number); } } %> <% if(Session.isnew ()) {countpeople (); } Integer Yournumber= (Integer)Application.getattribute ("Count"); %> <P></P>Welcome to visit this website, you are the first<%= Yournumber%>access to a user. </Body></HTML>
In the preceding code, the Synchronized keyword is used to avoid concurrency problems with application objects. In order to avoid the page refresh problem, added Session.isnew () to determine if the session object is new, indicating that the user began to access the system, the counter is added 1, when the user refreshes the current page, because the session object is not new, so avoid the problem of repetition plus 1
In fact, in implementing the Counter function, you need to be aware of some details, such as frequent refreshes and concurrent access. Because the life cycle of the Application object is related to server start and stop, application saved counters will be emptied if the server restarts due to a problem. To resolve this problem, you can save the value of the counter in a file, and then add 1 to the counter by using the read-write file function.
JSP website Count function application session