5 application对象
对于一个容器而言,每个用户都共同使用一个application对象,这和session对象是不一样的,它用于实现用户间数据共享。服务器启动后,就会自动创建application对象,这个对象一直会保持,直到服务器关闭为止。
application对象常用方法如下表所示。
方法名称 | 说明 |
---|---|
setAttribute(String attName,Object value) | 设定指定名字属性值。 |
getAttribute(String attName) | 获取指定名字属性值。 |
Enumeration getAttributeNames() | 返回所有application对象的属性名字,结果是枚举类对象。 |
removeAttribute(String attName) | 删除指定属性。 |
String getRealPath(String path) | 返回虚拟路径的真实路径。 |
实例代码:
<%@ page pageEncoding="UTF-8"%>
<HTML>
<BODY>
<FORM action="messagePane.jsp" method="post" name="form">
输入您的名字:
<BR>
<INPUT type="text" name="peopleName">
<BR>
输入您的留言标题:
<BR>
<INPUT type="text" name="Title">
<BR>
输入您的留言:
<BR>
<TEXTAREA name="messages" ROWs="10" COLS="36"></TEXTAREA>
<BR>
<INPUT type="submit" value="提交信息" name="submit">
</FORM>
<FORM action="showMessage.jsp" method="post" name="form1">
<INPUT type="submit" value="查看留言板" name="look">
</FORM>
</BODY>
</HTML>
<%@ page import="java.util.*" pageEncoding="UTF-8" %>
<HTML><BODY>
<%! Vector<String> v=new Vector<String>();
int i=0; ServletContext application;
synchronized void sendMessage(String s)
{ application=getServletContext();
i++;
v.add("No."+i+","+s);
application.setAttribute("Mess",v);
}
%>
<% String name=request.getParameter("peopleName");
String title=request.getParameter("Title");
String messages=request.getParameter("messages");
if(name==null)
{name="guest"+(int)(Math.random()*10000);
}
else
{byte a[]=name.getBytes("ISO-8859-1");
name=new String(a);
}
if(title==null)
{title="无标题";
}
else
{byte a[]=title.getBytes("ISO-8859-1");
title=new String(a);
}
if(messages==null)
{messages="无信息";
}
else
{byte a[]=messages.getBytes("ISO-8859-1");
messages=new String(a);
}
String s="姓名:"+name+"#"+"标题:"+title+"#"+"内容:"+"<BR>"+messages;
sendMessage(s);
out.print("您的信息已经提交!");
%>
<A HREF="third_example5.jsp" >返回
</BODY></HTML>
<%@ page import="java.util.*" pageEncoding="UTF-8" %>
<HTML><BODY>
<% Vector v=(Vector)application.getAttribute("Mess");
for(int i=0;i<v.size();i++)
{ String message=(String)v.elementAt(i);
StringTokenizer fenxi=new StringTokenizer(message,"#");
while(fenxi.hasMoreTokens())
{ String str=fenxi.nextToken();
out.print("<BR>"+str);
}
}
%>
</BODY></HTML>
程序说明:
ServletContext application;
application=getServletContext();
得到application对象。
运行结果:
运行后如图所示,输入内容单击“提交信息”按钮,之后单击“查看留言板”按钮
点击提交信息:
查看留言板消息: