ServletContext(不同用户在服务器端共享数据)

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>");


 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值