ServletContext(String,Object)
1:使用:
1:如何得到ServletContext实例
ServletContext sc = this.getServletContext();
2:添加属性sc.setAttribute(String name, Object ob);
得到值sc.getAttribute(String name); 返回Object
删除属性removeAttribute(String name);
3:生命周期
ServletContext中的生命周期从创建开始,到服务器关闭而结束。
2:用途:
1:网站计数器
2:网站在线用户显示
3:简单的聊天系统
3:例:网站计数器;
问题:各个用户每登陆成功一次,就要去操作一次文件,这样效率低下,所以要减少操作文件的次数
可以在init()方法中初始化servletContext中属性times对应的初始值
public void init() throws ServletException {
// 只会被调用一次
//添加网页访问计数器的功能
try {
FileReader f1 = new FileReader("f:\\myCounter.txt");
BufferedReader bw1 = new BufferedReader(f1);
String numVal = bw1.readLine();
bw1.close();
//将times值放入servletContext中
this.getServletContext().setAttribute("visitTimes", numVal);
} catch (Exception e) {
e.printStackTrace();
}
}
可以再destory()方法中,一次性的将servletContext中属性times对应的值写入文件中。
public void destroy() {
//将新的次数写回文件
try {
FileWriter f2 = new FileWriter("f:\\myCounter.txt");
BufferedWriter bw2= new BufferedWriter(f2);
bw2.write(this.getServletContext().getAttribute("visitTimes").toString());
bw2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
计数器加1操作
//将servletContext中的visitTimes对应的值加1
String times = this.getServletContext().getAttribute("visitTimes").toString();
//对times值加再放回servletContext
this.getServletContext().setAttribute("visitTimes", Integer.parseInt(times)+1+"");//变成int再变成string
客户端显示
out.println("该网页被访问了"+this.getServletContext().getAttribute("visitTimes").toString()+"次<br>");