ServletContext的理解

ServletContext的设置和获取与Session极其类似,他们同样处于服务端

但他们的区别在于,

ServletContext是所有浏览器客户端共享,而Session在有效期内,则仅针对一个浏览器访问有效

两者都占用服务器内存,故要精细使用。

ServletContext应用场景:

1.网站访问计数器

2.在线计数

3.简单的聊天系统

......

//添加网页访问次数的功能
//获取当前次数
FileReader fr = null;
BufferedReader bfr = null;
int times = 0;
try
{
  fr = new FileReader("D:\Data.txt");
  bfr = new BufferedReader(fr);
  sCount = bfr.readLine();
  times = Integer.parseInt(sCount);
  times++;
}catch(Exception e){
}finally{
  if (bfr != null)
    bfr.close();
}
//再将新的次数写回文件
FileWriter fw = null;
BufferedWriter bfw = null;
try{
  fw = new FileWriter("D:\Data.txt");
  bfw = new BufferedWriter(fw);
  bfw.write("" + times);               //改行要特别注意,要转化为字符串写入,直接写times, 虽然语法不报错,但是效果不对,折腾人啊
}catch(Exception e){
}
finally{
  if (bfw != null)
    bfw.close();
}

原文地址:https://www.cnblogs.com/jiqiwoniu/p/4403972.html