過濾器、監聽器應用之網站訪問量

<pre name="code" class="java">public class CountFilter implements Filter {
    public CountFilter() {
    }
    
	public void destroy() {
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
<span style="white-space:pre">		</span>//此處單開一個線程統計訪問量,可以加快正常內容的訪問速度,但統計的實時性沒那麼好
		new MyThread(request.getServletContext()).start();
		chain.doFilter(request, response);
	}
	public void init(FilterConfig fConfig) throws ServletException {
	}

}

class MyThread extends Thread{
	private ServletContext context;
	private static Object obj = new Object();
	
	public MyThread(ServletContext context) {
		this.context = context;
	}

	@Override
	public void run() {
		synchronized (obj) {
			Integer count = (Integer) context.getAttribute("count");
			if (count == null) {
				count = new Integer(0);
			}
			count++;
			context.setAttribute("count", count);
		}
	}
	



public class MyservletContextListener implements ServletContextListener {

	@Override<span style="color:#ff0000;">//服務器項目啓動時從文件中讀取出上次保存的訪問量</span>
	public void contextInitialized(ServletContextEvent sce) {
		try {
			String path =  sce.getServletContext().getRealPath("count.txt");
			BufferedReader br = new BufferedReader(new FileReader(path));
			String line = br.readLine();
			Integer count = Integer.valueOf(line);
			sce.getServletContext().setAttribute("count", count);
			br.close();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override<span style="color:#ff0000;">//服務器關閉時將訪問量保存到文件</span>
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			String path =  sce.getServletContext().getRealPath("count.txt");
			String count = ""+sce.getServletContext().getAttribute("count");
			PrintWriter pw = new PrintWriter(path);
			pw.println(count);
			pw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}



發佈了76 篇原創文章 · 獲贊 53 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章