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>

  • 相关阅读:
    输入和输出

    4. 深入 Python 流程控制
    js下拉框选择图片
    按下enter触发事件
    js多种方法取数组的最后一个元素
    apply,call,bind函数作用与用法
    vue中的js绑定样式
    js添加删除class
    rem等比例自适应手机尺寸
  • 原文地址:https://www.cnblogs.com/danyuzhu11/p/6741942.html
Copyright © 2011-2022 走看看