<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="javax.servlet.*" %>
<html>
<head>
<title>网站计数器</title>
</head>
<body>
<%!
synchronized void countPeople()
{ // 串行化计数函数
ServletContext application=((HttpServlet)(this)).getServletContext();
Integer number=(Integer)application.getAttribute("Count");
if(number==null)
{ // 如果是第1个访问本站
number=new Integer(1);
application.setAttribute("Count", number);
}
else
{
number=new Integer(number.intValue()+1);
application.setAttribute("Count",number);
}
}
%>
<%
if(session.isNew())
{ // 如果是一个新的会话
out.println("是一个新会话!");
countPeople();
}
Integer yourNumber=(Integer)application.getAttribute("Count");
out.println(yourNumber);
%>
<p>欢迎访问本站,你是第
<%=yourNumber %>
个访问用户。
</body>
</html>
程序利用synchronize关键字对计数函数进行了串行化(有的书中叫序列化),以确保当两个客户端同时访问网页而修改计数值时不会产生冲突;getServletContext()方法来得到application对象,因为有些Web服务器并不直接支持application对象,必须先得到其上下文;如果还是第一个访问的客户,则前面代码中得到的number会是空值,故置初始值为1,否则做增1处理;如果是一个新的会话则调用计数函数,得到计数值并将其显示。
可以发现,当刷新页面时,其数值并不会增加,只有关闭了本网站的所有窗口再重新访问时,才会增1,因为这又是一个新的会话。