JAVA学习笔记_分IP统计访问次数

listener

    public void contextInitialized(ServletContextEvent sce)  { 

        ServletContext context = sce.getServletContext();
        //counts:IP+访问次数(一次回话记一次)
        HashMap<String,Integer> counts = new HashMap<String,Integer>();
        context.setAttribute("map", counts);
        Integer totalcounts = 0;//各个IP总访问次数
        context.setAttribute("total", totalcounts);
    }

filter

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest req = (HttpServletRequest) request;

        String client = req.getRemoteAddr();

        HttpSession s = req.getSession();
        ServletContext application = req.getServletContext();
        Map<String,Integer> counts = (Map<String, Integer>) application.getAttribute("map");

        System.out.println("访问是否是新会话:    "+s.isNew());

        Integer totalcounts = (Integer) application.getAttribute("total");

            if(counts.containsKey(client)){
                //新会话,访问次数加一
                if(s.isNew()){

                    Integer times = counts.get(client);
                    counts.put(client, times+1);
                }

            }else{
                application.setAttribute("total", totalcounts+1);
                counts.put(client, 1);
            }


            Set<Entry<String, Integer>>  entry = counts.entrySet();
            for (Entry<String, Integer> entry2 : entry) {

                System.out.print(entry2.getKey()+"     ");
                System.out.println(entry2.getValue());
            }


            totalcounts = (Integer) application.getAttribute("total");
            System.out.println("总访问IP数:   "+totalcounts);
        System.out.println("======================================");

        chain.doFilter(request, response);
    }
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页