ServletContextListener监听器

public class Counter{
private int count;
public Counter(){}
public Counter(int count){
this.count=count;
}
public int getCount(){
return count;
}
public void setCount(){
this.count=count;
}
public int add(int step){
count+=step;
}
}




public class CounterServlet extends HttpServlet{
public void doGet(HttpServletRequet request,HttpServletResponse response)throws IOException,ServletException{
//获取ServletContext的引用
ServletContext context=getContext();
Counter counter=context.getAttribute("counter");
//初始化ServletContext中没有counter属性,或创建counter属性
if(counter==null){
counter=new Counter();
context.setAttribute("counter",counter);
}
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();
out.println("<html><head><title>CounterServlet</title></head>");
out.println("<body>");
out.println("<h1>欢迎,你是第"+counter+"位访问者"+"</h1>");
out.println("</body></html>");
counter.add(1);//将计数器递增为1
out.close();
}
}


//MyServletContextListener
public class MyServletContextListener implements ServletContextListener{


public void contextInitialized(ServletContextEvent sce){


System.out.pritln("applicaiton is initialized...");

//获取ServletContext对象
ServletContext context=getServletContext();

try{
//从文件中读取计数器的值
BufferedReader reader=new BufferedReader(new InputStreamReader(context.getResourceAsStream("/count/count.txt")));
int count=Integer.parseInt(reader.readLine());
reader.close();
//创建计数器对象
Counter counter=new Counter(counter);
//把计数器对象保存到web应用范围
context.setAttribute("counter",counter);


}catch(IOException e){
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent sce){
System.out.println("application is Destoryed...");
//获取ServletContext对象引用
ServletContext context=sce.getContext();
//从web应用中获取计数器对象
Counter counter=(Counter)context.getAttribute("counter");
if(count!=null){
//把计数器的值写会到context.txt文件中去
String filepath=context.getRealPath("/count");
filepath=filepath+"/count.txt";
PrintWriter pw=response.getWriter(filepath);
pw.println(counter.getCount());
pw.close();
}
}
}







































































































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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值