首页 > 代码库 > ServletContextListener监听器

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();
}
}
}







































































































ServletContextListener监听器