I tried to use application object to record how many visitors have viewed this page,but after I refreshed the page I closed the browser,and when I open the browser again to view this page,the record back to the number I started to refresh.I don’t know why?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<html>
<body>
<%
Integer count;
synchronized (application) {
count = (Integer) application.getAttribute("count");
if(count == null)
count = new Integer(0);
count = new Integer(count.intValue() + 1);
application.setAttribute("count", count);
}
%>
This page has been visited <%= count.intValue() %> times!
</body>
</html>
Why have synchronized? Why dont you just use a global variable (ie java
static)?You don’t have to worry about threads on the web-server. It should handle that.
A global variable on the server will be the same for all threads.
Sample here http://www.tutorialspoint.com/jsp/jsp_hits_counter.htm
which says to use :
then get it with ..
An example:
with