<1> 什么是application?
application 代表整个web程序, 整个服务器端只存在一个application对象, 当Tomcat启动的时候就被创建
application 的生命周期与Tomcat 同步
<2> 使用application储存网站当前登录人数, 并显示在首页
1. 在login_do中:
<%
if(user == null){
// 登录失败, 略
}else{
// 登陆成功
int number = 0;
if(application.getAttribute("userNumber") != null){ // 为了避免返回空值而产生的错误
number = (Integer)application.getAttribute("userNumber");
}
number++;
application.setAttribute("userNumber",number);
}
2. 在index.jsp中:
<%
Object o2 = application.getAttribute("userNumber");
if(o2 != null){
out.println("当前登录用户: " + o2 + "个!<br/>")
}
%>
效果: