JSP内置对象application
我们学习了session对象,使用session可以保存当前每个用户的会话状态信息,一个用户对应一个session。但是如果要存在这样一个数据,如应用的访问人数,需要Web应用系统中的所有用户共享,这就需要用到JSP的另一个对象——application对象。
application对象
application对象类似于系统的全局变量,用于同一个应用内的所有用户之间的数据共享。
示例:统计网页的访问人数:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Integer count = (Integer) application.getAttribute("count");
if(count!=null){
count=count+1;
}else{
count=1;
}
application.setAttribute("count", count);
count = (Integer) application.getAttribute("count");
out.print("统计访问量:目前有"+count+"个人访问过此网站");
%>
</body>
</html
说明:这里使用count存储统计的访问人数,由于无法控制是第几个用户访问本站,所以先通过getAttribute()方法取值进行判断,如果count为null,说明是第一个用户,赋值为1,否则在原来的计数上累加。
对象的作用域
page的作用域
page作用域指单一的JSP页面范围,page作用域内的对象只能在创建该对象的页面中访问。page作用域可以使用pageContext对象的setAttribute()和getAttrbute()方法访问。page作用域在客户端每次请求JSP页面时创建,在服务器发送响应或请求转发到其他页面或资源后失效。演示代码如下所示:
testOne.jsp页面代码如下:
<body>
<%
String name="page";
pageContext.setAttribute("name", name);
%>
<strong>
testOne:<%=pageContext.getAttribute("name") %>
</strong>
<br/>
<