假如有這么一個需求,要記錄所有用戶訪問某一頁面的次數。
最先想到的可能是在該Controller定義一個靜態成員,然后在相應Action里自增。但這樣有一個問題,就是Tomcat或者其他服務器重啟的話,這個值是沒辦法保存的。
當然在數據庫中直接保存也是可以的,但因此便要去單獨建張表,日后用戶訪問相應頁面都要去訪問數據庫維護該表有點不值得。
利用自定義ServletContextListener可以很方便做到這一點。思路如下:
1 、在 Web 應用啟動時從文件中讀取計數器的數值,並把表示計數器的 Counter 對象存放到 Web應用范圍內。存放計數器的文件的路徑為helloapp/count/count.txt 。
2 、在Web 應用終止時把Web 應用范圍內的計數器的數值保存到count.txt 文件中。
public class MyServletContextListener implements ServletContextListener{ public void contextInitialized(ServletContextEvent sce){ System.out.println("helloapp application is Initialized."); // 獲取 ServletContext 對象 ServletContext context=sce.getServletContext(); try{ // 從文件中讀取計數器的數值 BufferedReader reader=new BufferedReader( new InputStreamReader(context. getResourceAsStream("/count/count.txt"))); int count=Integer.parseInt(reader.readLine()); reader.close(); // 把計數器對象保存到 Web 應用范圍 context.setAttribute("count",count); } catch(IOException e) { e.printStackTrace(); } } public void contextDestroyed(ServletContextEvent sce){ System.out.println("helloapp application is Destroyed."); // 獲取 ServletContext 對象 ServletContext context=sce.getServletContext(); // 從 Web 應用范圍獲得計數器 int count=(int)context.getAttribute("count"); if(count!=0){ try{ // 把計數器的數值寫到 count.txt 文件中 String filepath=context.getRealPath("/count"); filepath=filepath+"/count.txt"; PrintWriter pw=new PrintWriter(filepath); pw.println(count); pw.close(); } catch(IOException e) { e.printStackTrace(); } } } }
同時在web.xml文件中要配置
<listener> <listener-class> ServletContextTest.MyServletContextListener<listener-class /> </listener>
通過ServletContext對象便能獲取到保存的count值。