application
application对象实现了用户数据的共享。可存放全局变量。生命周期开始于服务器启动,结束于服务器的关闭,在关闭前是一直存在的;这样在用户的前后连接或不同用户之间的连接中,可以对此对象的同一属性进行操作,在任何地方对此对象属性的操作,都将影响到其他用户对此的访问,服务器的启动和关闭 决定了application对象的生命。
服务器启动时产生了application对象,当客户浏览网站的各个页面,application都是同一个,所有客户都是访问共用这个内置对象。
一、几个常用的方法
服务器信息:<%= application.getServerInfo() %>
用户名称:<%= application.getServletContextName() %>
二、重要的用法
1.设置和取application
<!--返回与此会话中指定名称绑定在一起的对象counter,如果没有对象绑定在该名称下,返回null-->
<%
Object obj=application.getAttribute("counter");
%>
<!--使用指定名称将对象绑定counter中-->
<%
application.setAttribute("counter", new Integer(1));
%>
2.获取application所有属性
<%
Enumeration a=application.getAttributeNames();
%>
例子
<%
application.setAttribute("city","厦门");
application.setAttribute("postcode","10000");
application.setAttribute("email","123@qq.com");
%>
获取城市:<%=application.getAttribute("city") %>
显示application中所有属性:
<%
Enumeration a=application.getAttributeNames();
while(a.hasMoreElements()){
out.println(a.nextElement()+" <br>");
}
%>
(1)hasMoreElements
boolean hasMoreElements()测试此枚举是否包含更多的元素。
返回:
当且仅当此枚举对象至少还包含一个可提供的元素时,才返回 true;否则返回 false。
(2)nextElement
E nextElement()如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。
返回:
此枚举的下一个元素。
3.删除application内容
<%
application.removeAttribute("usernae");
application.removeAttribute("password");
%>
三、application的一个计数器
<%
Object obj=application.getAttribute("counter");//在application中取得couter
if(obj==null){
application.setAttribute("counter",new Integer(1));//将1赋值给counter,存储在application中
out.println("该页面访问了1次</br>");
}
else{
int counterValue=Integer.parseInt(obj.toString());//解析成十进制的数,toString()返回此对象的字符串表示形式
counterValue++;
out.println("该页面访问了"+counterValue+"次</br>");
application.setAttribute("counter",counterValue);
}
%>