• Java过滤ip,只允许配置的ip能够被访问


    Java过滤ip,只允许配置的ip能够被访问

    第一先创建过滤类 实现Filter就会有init(),doFilter(),destroy()三个方法

    private String ips;
    
        public String getIps() {
            return ips;
        }
    
        public void setIps(String ips) {
            this.ips = ips;
        }
    
        public ipConfigFilter(String ips) {
            this.ips = ips;
        }
    
        public ipConfigFilter() {
            this.ips = "";
        }
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            ips = filterConfig.getInitParameter("ips");
            String[] ipList = this.getIps().split(",");
            for (String ip : ipList) {
                logger.debug(ip);
            }
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            String[] ipList = this.getIps().split(",");
            String invokerIp = request.getRemoteAddr();
    
            logger.debug("remot:" + invokerIp);
            boolean falg = Arrays.asList(ipList).contains(invokerIp);
            if (!falg) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print("{'code':'401','msg':'您无权限访问该地址'}");
            } else {
                chain.doFilter(request, response);
            }
    
        }
    
        @Override
        public void destroy() {
    
        }
    

      在web.xml里配置过滤信息

      param-value可以配多个用逗号隔开
      
     <filter>
            <filter-name>ipConfigFilter</filter-name>
            <filter-class>com.Filter.ipConfigFilter</filter-class>
            <async-supported>true</async-supported>
            <init-param>
                <param-name>ips</param-name>
                <param-value>10.1000.100.100,20.100.100.100</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>ipConfigFilter</filter-name>
            <url-pattern>/page/pc-back/*</url-pattern>
        </filter-mapping>
        <session-config>
            <session-timeout>30</session-timeout>
        </session-config>
    

      

  • 相关阅读:
    Linux服务器基本信息查看
    Linxu下jenkins部署和基本配置
    Python常见序列详解
    Git 操作
    Python操作Mongodb
    sqlalchemy ORM模块使用介绍
    linux之sed的常用操作
    Python pandas学习笔记
    正则表达式——字符串匹配
    1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,...输入位置输出该位置上的数字,如输入10输出4,输入11输出5.
  • 原文地址:https://www.cnblogs.com/yyKong/p/13941477.html
Copyright © 2020-2023  润新知