JavaWeb——服务器访问量数据读取与保存

ServletContextListener

 1 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.util.Properties;
 6 
 7 import javax.servlet.ServletContext;
 8 import javax.servlet.ServletContextEvent;
 9 import javax.servlet.ServletContextListener;
10 
11 /**
12  * 服务器访问量数据读取与保存
13  * @author Administrator
14  *
15  */
16 public class MyServletContextListener implements ServletContextListener {
17     private Properties pro = new Properties();
18     @Override
19     public void contextDestroyed(ServletContextEvent sce) {
20         try {
21             // 从应用上下文库中去除当前访问量数据
22             ServletContext sct = sce.getServletContext();
23     
24             Integer times = (Integer) sct.getAttribute("times");
25             // 把当前访问量数据做持久化操作
26              pro.setProperty("times", times.toString());
27             String path = sct.getRealPath("/pagecounter.properties");
28             pro.store(new FileOutputStream(path), null);
29         } catch (Exception e) {
30             e.printStackTrace();
31         }
32     }
33 
34     @Override
35     public void contextInitialized(ServletContextEvent sce) {
36 
37         try {
38             // 读取初始化的访问量
39             ServletContext sct = sce.getServletContext();
40             String path = sct.getRealPath("/pagecounter.properties");
41             pro.load(new FileInputStream(path));
42             Integer times = Integer.parseInt(pro.getProperty("times"));
43             // 放到上下文仓库中
44             sct.setAttribute("times", times);
45             System.out.println("第" + times + "访问");
46         } catch (Exception e) {
47             e.printStackTrace();
48         }
49     }
50 
51 }

Servlet代码

 1  2 
 3 import java.io.IOException;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.annotation.WebServlet;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 
11 @WebServlet("/IndexServlet")
12 public class IndexServlet extends HttpServlet {
13     
14     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         //从应用上下文仓库去除访问量数据
16         Integer times =  (Integer) this.getServletContext().getAttribute("times");
17         //基于此访问量数据+1
18         times+=1;
19         //把当前计算后的访问量数据放回上下文仓库中
20         this.getServletContext().setAttribute("times", times);
21     
22     }
23 
24 
25     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
26         
27         doGet(request, response);
28     }
29 
30 }

web.xml设置

1   <listener>
2     <listener-class>homeservlet1106.ServletContextListener.MyServletContextListener</listener-class>
3   </listener>

 

posted @ 2019-11-06 14:14  谢世林  阅读(557)  评论(0)    收藏  举报