application 对象用来在多个程序或者是多个用户之间共享数据,用户使用的所有的application对象的作用都是一样的.这与session对象不同.服务器一旦启动,就会自动创建application对象,并一直保持下去,直至服务器关闭,而application会自动消失,不需要麻烦垃圾回收机制.
对于application对象的方法我就不啰嗦了,下面我们来看两个例子,一个是没有使用application对象做的一个简单的网站计数器,具体点代码如下:
- <span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>网站计数器</title>
- </head>
- <body>
- <%!int counter=0;
- synchronized void counterFunction()
- {
- counter++;
-
- }
- %>
- <%counterFunction(); %>
- 欢迎访问本站,你是第<%=counter %>个访问用户.
- </body>
- </html></span>
效果图为:

当我们再次刷新也时,我们将会看到访问人数从1增加到2了,如图所示:

从结果上来看,这个简单的网站计数器并不精确,访问人数应该是根据是否是一个新的会话来判断是否是一个新访问网站的用户,而不是刷新一次,就增加一个网站的新访问用户,application 对象则可以用来保存访问人数.具体的代码如下:
- <span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ page import="javax.servlet.*" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>网站计数器</title>
- </head>
- <body>
- <%!
- synchronized void countPeople(){
- ServletContext application=((HttpServlet)(this)).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);
- }
- }
- %>
- <%
- if(session.isNew())
- countPeople();
- Integer yourNumber=(Integer)application.getAttribute("Count");
- %>
- <p><p> 欢迎访问本站,你是第<%=yourNumber %>个访问用户.
-
- </body>
- </html></span>
效果图为:

我们来看看刷新一下,用户增加的情况,如图所示:

重新打开一个页面,用户增加的情况,如图所示:

从两个对比的例子,我们可以看出来,要想把自己的东西做到比较准确,我们就要善于站在巨人的肩膀上,使用好别人封装好的方法或者类,用着方便而且准确性还高.