一、JSP内置对象application
1.application对象简介
2.application对象中的常用方法
3.application对象属性范围
二、具体实现
1.实现功能
2.实现步骤
三、完整代码
一、JSP内置对象application
1.application对象简介
application对象与session对象相似,当一个用户首次访问服务器 上的一个JSP页面时,服务器的JSP引擎就为该用户创建了application对象,当客户在服务器的各个页面之间浏览时,这个application对象都是同一个,直到服务器关闭。但是与session对象不同的是,所有用户的application对象都是同一个,即所有用户共享这个application对象。application对象由服务器创建,也由服务器自动清除,不能被用户创建和清除。很多web网站都会计算网站的访问量,在计算网站访问量时,最佳使用对象就是application对象。
2.application对象中的常用方法
String getRealPath(String path):得到虚拟目录对应的绝对路径。
public Enumeration getAttributeNames():得到所有属性的名称。
public String getContextPath():取得当前的虚拟路径名称。
3.application对象属性范围(用一张图来表示)
所有用户都可以取得此信息,此信息在整个服务器上被保留。
二、具体实现
1.实现功能
当一个用户访问该页面时,输出您是第几位访问者,每一位新用 户访问该页面,访问量加一,当用户刷新该页面时,访问量不变。
2.实现步骤
向application对象中添加属性count用来存储网站访问用户数量。
当户用访问页面时,属性count的值加一。
当用户再次刷新网页时,属性count的值不变。
三、完整代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>网站访问量计数器</title>
</head>
<body>
<%
if(session.getAttribute("visit")==null){
session.setAttribute("visit", "y");//将未访问设置为访问
String strCount = (String) application.getAttribute("count");
int count =0;
if(strCount!=null)
count = Integer.parseInt(strCount)+1;
else
count++;
application.setAttribute("count",String.valueOf(count));
%>
<%}%>
您是第<%=application.getAttribute("count") %>位访问者!
</body>
</html>