zoukankan      html  css  js  c++  java
  • 分ip统计访问次数

    1、创建一个过滤器

    public class AFilter implements Filter {
    private FilterConfig filterconfig;

    @Override
    public void destroy() {
    System.out.println("死翘翘了");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
    /**
    * 从application中得到map
    * 从request中获取客户端ip
    * 查看map中是否存在这个IP,进行计算
    */
    //得到application

    ServletContext app=filterconfig.getServletContext();
    Map<String ,Integer> map=(Map<String ,Integer>)app.getAttribute("map");
    //获取客户端的ip
    String ip=request.getRemoteAddr();
    //判断
    if(map.containsKey(ip)){
    int count=map.get(ip);
    map.put(ip, count+1);
    }else{
    map.put(ip, 1);


    }

    app.setAttribute("map", map);

    chain.doFilter(request, response); //至进行统计,放行
    }

    @Override
    public void init(FilterConfig fconfig) throws ServletException {
    System.out.println("过滤器畜生");
    //创建之后马上执行,用作初始化,服务器启动就会执行,而且指执行一次


    this.filterconfig=fconfig;
    }

    -----------------------------------------------------------------------

    2、新建一个监听

    public class Alisten implements ServletContextListener {

    public Alisten() {

    }

    /**
    * 在服务器启动时创建Map,保存到ServletContext
    */

    public void contextInitialized(ServletContextEvent sce) {
    // 创建map

    Map<String, Integer> map = new LinkedHashMap<String, Integer>();
    // 得到ServletContext
    ServletContext application = sce.getServletContext();
    application.setAttribute("map", map);
    }

    public void contextDestroyed(ServletContextEvent arg0) {

    }

    -------------------------------------------------------------------

    3、写一个jsp页面

    <body>
    <h1 align="center">显示结果</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>
    </c:forEach>
    </table>
    </body>

  • 相关阅读:
    MySQL LIMIT OFFSET
    Sublime Text 3安装清爽主题(著名的Soda Theme)
    MySQL无法远程连接解决方案
    算法题:李嘉诚保险柜密码问题
    一些不错的算法学习练习站点
    [转]MySQL远程连接ERROR 2003 (HY000):Can't connect to MySQL server on'XXXXX'(111) 的问题
    使用什么工具连接MySQL Server
    CentOS 7修改MySQL 5.6字符集为UTF-8
    CentOS 7 Minimal编译安装MySQL5.6
    如何使浏览器默认下载文件而不是打开文件
  • 原文地址:https://www.cnblogs.com/danyuzhu11/p/6741942.html
Copyright © 2011-2022 走看看