application详解及实例
application对象用来在多个程序或者是多个用户之间共享数据,用户使用的所有application对象都是一样的,这与session对象不同。服务器一旦启动,就会自动创建application对象,并一直保持下去,直至服务器关闭,application就会自动消失。
application对象的方法
application对象实现了javax.servlet.ServletContext接口,此接口位于servlet-api.jar包中,代表当前web应用上下文。application对象的常用方法有如下一些。
实例 网站计数器
代码如下:
<%@ 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())//如果是一个新的会话
countPeople();
Integer yourNumber=(Integer)application.getAttribute("Count"); %>
<P><P>欢迎访问本站,你是第
<%=yourNumber%>
个访问用户。
</BODY>
</HTML>
程序用synchronize关键字对计数函数进行了串行化(或者叫序列化),以确保当两个客户端同时访问网页而修改计数值时不会产生冲突;getServletContext()方法来得到application对象,因为有些Web服务器并不直接支持application对象,必须先得到其上下文;如果还是第一个访问的客户,则前面代码中得到的number会是空值,故置初值为1,否则做增1处理;如果是一个新的会话则调用计数函数,得到计数值并将其显示。网站计数器程序的运行结果如下图所示:
第一次访问:
关闭浏览器后,再次访问:
Java_Web轻量级开发全体验