在前一篇里我们讲了在JSP 中使用session 来保存每个用户的私有信息,但有时服务器需要管理面向整个应用的参数,使得每个客户都能获得同样的参数值。那在JSP中应怎么办呢?和Session 一样, JSP使用Application 对象,操作的方法和Session "Times New Roman"一样。
其API 使用如下:
Application .setAttribute("Item", ItemValue); //设置一个应用变量
Integer i=(Integer) Application.getAttribute("ItemName"); // 得到//item
现以一个简单统计在线人数的的例子来说明Application的应用(这里不考虑离开的情况),init.jsp(初始化),count.jsp( 统计总人数并输出)。
init.jsp
代码
- <HTML>
- <HEAD>
- <TITLE> New Document </TITLE>
- <BODY BGCOLOR="#FFFFFF">
- <%
- application.setAttribute("counter",new Integer(0));
- out.println(application.getAttribute("counter"));
- %>
- </BODY>
- </HTML>
- count.jsp
- <HTML>
- <HEAD>
- <TITLE> New Document </TITLE>
- </HEAD>
- <BODY BGCOLOR="#FFFFFF">
- <%
- Integer i=(Integer)application.getAttribute("counter");
- i=new Integer(i.intValue()+1);
- application.setAttribute("counter",i);
- out.println((Integer)application.getAttribute("counter"));
- %>
- </BODY>
- </HTML>