application对象的应用案例

时间:2023-03-08 23:39:03
application对象的应用案例

application对象由多个客户端用户共享,它的应用范围是所有的客户,服务器启动后,新建一个application对象,该对象一旦建立,就一直保持到服务器关闭。当有客户访问服务器上的一个JSP页面时,JSP引擎为该客户分配已建立的application对象;当客户在所访问站点的不同页面浏览时,其application是同一个,直到服务器关闭。

application对象与session对象的不同之处在于:不同的客户拥有不同的session对象,而所有的客户拥有同一个application对象。所以可以用application对象保存服务器运行时的全局数据,例如,页面访问次数

例子:counter.jsp

<body>
<%!synchronized void countPeople()
{
ServletContext application=getServletContext();
Integer number=(Integer)application.getAttribute("Count");
if(number==null)
{
number=new Integer(1);
application.setAttribute("Count",number);
}else{
number=new Integer(number.intValue()+1);
application.setAttribute("Count", number);
}
}
%>
<%!Integer yournumber=0; %>
<%
if(session.isNew())
{
countPeople();
yournumber=(Integer)application.getAttribute("Count");
}
%>
<p>
<p>
欢迎访问本站,您是<%=yournumber%>个访问用户
</body>

application对象的应用案例