JSP简单练习-站点计数器

时间:2024-07-27 17:36:02
<%@ 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>

程序利用synchronizekeyword对计数函数进行了串行化(有的书中叫序列化),以确保当两个client同一时候訪问网页而改动计数值时不会产生冲突;getServletContext()方法来得到application对象,由于有些Webserver并不直接支持application对象,必须先得到其上下文;假设还是第一个訪问的客户,则前面代码中得到的number会是空值,故置初始值为1,否则做增1处理;假设是一个新的会话则调用计数函数,得到计数值并将其显示。

能够发现,当刷新页面时,其数值并不会添加,仅仅有关闭了本站点的全部窗体再又一次訪问时,才会增1,由于这又是一个新的会话。