1、application是javax.servlet.ServletContext接口的实例化对象!
application内置对象是用于保存所有应用程序中的公有数据!服务器启动后自动创建application对象后,只要没有关闭服务器则application对象一直存在,并且服务器上面的所有客户端都可以共享!
2、application的主要操作
- getRealPath() 得到虚拟目录的绝对路径!
- getAttributeNames() 得到所有属性的名称!
- getContextPath() 取得当前虚拟路径的名称!
- setAttribute()、get/remove
3、网站计数器
- 因为访问一个网站人数可能过多,所以必须使用大整数类 Biglnteger
- 用户第一次访问才进行的技术操作,所以访问之前使用isNew()方法去进行判断是否为新用户!
- 进行更改,保存需进行同步操作!
- 代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.* "%>
<%@ page import="java.util.*" %>
<%@ page import="java.math.*" %>
<!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>Insert title here</title>
</head>
<body>
<%!
BigInteger count =null;
%>
<%!
//将所有操作属性全部定义在方法之中!
public BigInteger load(File f){
BigInteger count =null;//接受数据
try{
if(f.exists()){
Scanner s=new Scanner(new FileInputStream(f));
if(s.hasNext()){
count=new BigInteger(s.next());
s.close();
}
}else{//应该保存一个新的
count=new BigInteger("0");
save(f,count);//保存一个新的文件
}
}catch(Exception e){
e.printStackTrace();
}
return count;
}
%>
<%!
public void save(File f,BigInteger count){
try{
PrintStream p=null;
p=new PrintStream(new FileOutputStream(f));
p.println(count);
p.close();
}catch(Exception e){
e.printStackTrace();
}
}
%>
<%
String fn=this.getServletContext().getRealPath("/")
+"count.txt";
File f1=new File(fn);
if(session.isNew()){
synchronized(this){
count=load(f1);
count=count.add(new BigInteger("1")) ;
save(f1,count);
}
}
%>
<h2>您是第<%=count==null?0:count %>位访客!!!</h2>
</body>
</html>