javaWeb项目加入IP黑白名单

发布时间:2020-07-16 02:33:27 作者:HHT15927087748
来源:网络 阅读:1325

第一步:先在项目src文件下建立一个ipConfig.properties文件,加入黑白名单的ip

1)ipConfig.properties:

#单个IP地址的配置,多个之间用逗号或分好隔开
allowIP=192.168.1.15;127.0.0.1;
#IP地址区间方式的配置,多个区间用逗号或分好隔开
allowIPRange=172.20.32.10-172.20.32.11;172.20.32.88-172.20.32.89;
#通配符,多个用逗号或分好隔开
allowIPWildcard=192.168.1.*;

二,建IpFilter,过滤器文件
/**

}
//打印输出allowList
for(String str : allowList) {
System.out.println(str);
}
}

/** * 对配置文件进行校验 
  * @author hht * 
 * @serialData 2018-09-28 *
 *  @param allowIP 
 *   @param allowIPRange 
 *   @param allowIPWildcard 
 * @return */ 
public Boolean validate(String allowIP, String allowIPRange, String allowIPWildcard) {
    Boolean result = false; 
    //IP地址每一段的正则 
    String regx = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"; 
    //整个ip的正则
    String ipRegx = regx + "\\." + regx + "\\."+ regx + "\\." + regx; 
    //对第一种方式进行校验 
    Pattern pattern = Pattern.compile("("+ipRegx+")|("+ipRegx+"(,|;))*"); 
    if(this.isNullorMatches(allowIP, pattern)){ 
        result = true; //匹配成功
        } else { 
        result = false; 

}
//对第二种方式进行校验
pattern = Pattern.compile("("+ipRegx+")\-("+ipRegx+")|" + "(("+ipRegx+")\-("+ipRegx+")(,|;))");
if(this.isNullorMatches(allowIPRange, pattern)){
result = true; //匹配成功
} else {
result = false;
}
//对第三种方式进行校验
pattern = Pattern.compile("("+regx+"\."+ regx+"\."+regx+"\."+ "\)|" + "("+regx+"\."+regx+"\."+regx+"\."+ "\(,|;))
");
if(this.isNullorMatches(allowIPWildcard, pattern)){
result = true; //匹配成功
} else {
result = false;
}
return result;
}

/** * 进行正则匹配 * 
 * @author hht * 
 * @serialData 2018-09-28 *
 *  @param allow * @return */ 
public Boolean isNullorMatches(String allow, Pattern pattern) {
    //如果为空,说明用户没添加该项,不做处理
    if(allow == null || "".equals(allow.trim())) { return true; } else {
    //在最后面没有,或;的给添上 
    if(!allow.endsWith(";") && !allow.endsWith(",")) { 
    allow += ";";
    }
    //如果匹配,则返回true
  if(pattern.matcher(allow).matches()) { 
    return true; 
    } 
} 
return false; 

}

}

三,在项目中web.xml配置文件中加入过滤配置

<!-- 过滤器 -->
<filter>
<filter-name>IPFilter</filter-name>
<filter-class>xxxx.IpFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>IPFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 结束过滤器 -->

推荐阅读:
  1. 利用shell自动将异常IP加入iptables黑名单
  2. PHP如何限制访问ip白名单

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

web ip 黑白名单

上一篇:jQuery插件入门学习—— 学习目标:写一个星级评分插件(trigger用法)

下一篇:用 Hystrix 构建高可用服务架构

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》