1. 程式人生 > >Entermomem的專欄

Entermomem的專欄

分ip統計網站的訪問次數

統計工作需要在所有資源之前都執行,那麼就可以放到Filter中了
我們的過濾器不打算做攔截操作。因為只是統計的
用什麼來裝載統計的資料? Map<String,Integer>
只要一個Map即可
Map什麼時候建立?(使用ServletContextListener,在伺服器啟動時完成建立,並儲存到ServletContext中)儲存在?(Map儲存到ServletContxt中   )
    Map需要在Filter中用來儲存資料
    Map需要在頁面中使用,列印Map中的資料

    因為一個網站可能有多個頁面,無論那個頁面被訪問,都要統計訪問次數,所以使用過濾器最為方便
    因為需要分ip統計,所以可以在過濾器中建立一個Map,使用ip為key,訪問次數為value。當有使用者訪問時,獲取請求的ip,如果ip在map中存在,說明以前訪問過,那麼在訪問次數上加1即可。如果不存在 設定次數為1
    把Map放在ServletContxt
/**
 * 進行統計工作,結果儲存到map中
 * 
 * @ClassName: AFilter
 * @Description: TODO
 * @author liuw
 * @date 2018年11月8日 上午11:32:25
 *
 */
public class AFilter implements Filter {
    private FilterConfig config;

    public AFilter() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain filterChain) throws IOException, ServletException {
        /*
         * 1、得到application中的map 2、從request中獲取當前客戶端的ip地址
         * 3、檢視map中是否存在這個ip對應的訪問次數,如果存在,把次數+1再儲存回去
         * 4、如果不存在這個ip,那麼說明是第一次訪問本站,設定訪問次數為1
         */
        /*
         * 1、得到application
         */
        ServletContext app = config.getServletContext();
        Map<String, Integer> map = (Map<String, Integer>) app
                .getAttribute("map");
        /*
         * 2、獲取客戶端的ip地址
         */
        String ip = req.getRemoteAddr();
        /*
         * 3、進行判斷
         */
        // 這個ip在map中存在,說明不是第一次訪問
        if (map.containsKey(ip)) {
            int cnt = map.get(ip);
            map.put(ip, cnt + 1);
            // 這個ip在map不存在,說明是第一次訪問
        } else {
            map.put(ip, 1);
        }
        // 把map再放回到app中
        app.setAttribute("map", map);
        // 肯定放行
        filterChain.doFilter(req, res);
    }

    /**
     * 在伺服器啟動時執行本方法,且只執行一次
     */
    public void init(FilterConfig fConfig) throws ServletException {
        this.config = fConfig;
    }

}
public class AListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {

    }

    // 在伺服器啟動時建立map,儲存到ServletContext中
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // 建立map
        Map<String, Integer> map = new LinkedHashMap<String, Integer>();
        // 得到ServletContext
        ServletContext app = servletContextEvent.getServletContext();
        // 把map儲存到application中
        app.setAttribute("map", map);
    }

}

顯示統計結果

 <body>
    <h1>顯示結果</h1>
    <table align="center" width="60%" border="1">
    <tr>
    	<td>IP</td>
    	<td>次數</td>
    </tr> 
    <c:forEach items="${applicationScope.map }" var="entry"/>
    <tr>
    	<td>${entry.key }</td>
    	<td>${entry.value }</td>
    </tr>
    	
    </table>
  </body>