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>

  • 相关阅读:
    restful接口设计规范总结
    SSM框架中,配置数据库连接的问题
    Java通过mysql-connector-java-8.0.11连接MySQL Server 8.0遇到的几个问题
    浅谈Spring的PropertyPlaceholderConfigurer
    过滤器与拦截器的区别
    SpringMVC的拦截器(Interceptor)和过滤器(Filter)的区别与联系
    SpringMVC中使用Interceptor拦截器
    mybatis中模糊查询的使用以及一些细节问题的注意事项
    mybatis generator(MyBatis的逆向工程)
    mybatis-generator生成逆向工程两种方式
  • 原文地址:https://www.cnblogs.com/danyuzhu11/p/6741942.html
Copyright © 2011-2022 走看看