我的这个项目用了SpringMVC
参考网上写了个IPFilter
/** * IP过滤器
* @author zytim
* ip-pattern中配置允许访问的IP范围,允许"*"和"-"
*/
public class IPFilter implements Filter {
private final static Logger logger = LoggerFactory.getLogger(IPFilter.class);
private String ipPattern;
public String getIpPattern() {
return ipPattern;
}
public void setIpPattern(String ipPattern) {
this.ipPattern = ipPattern;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.ipPattern =PropertyUtil.getProperty("ip-pattern");
//从properties配置文件中取参数,也可以从web.xml的param-value里取参数,参数以“;”隔开
//this.ipPattern = filterConfig.getInitParameter("ip-pattern");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String ip = request.getRemoteHost();
String reqUrl = ((HttpServletRequest) request).getRequestURI();
if (reqUrl.contains("nouser")) {
chain.doFilter(request, response);//进入下一个Filter
return;
}
if (validateIP(ip, ipPattern)) {
//logger.info(ip+" is Permissible.");
chain.doFilter(request, response);
}
else {
logger.info(ip+" 拒绝访问。");//日志记录
((HttpServletResponse) response).sendRedirect("/nouser.jsp");
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
/**
* IP校验方法
* 功能描述: ip地址权限校验,允许"192.168.1.*"和"192.169.1.0-254"格式
* @param ipStr 请求ip
* @param ipPattern 权限ip列表 以;隔开
* @return 校验是否通过
*
*/
public static boolean validateIP(String ipStr, String ipPattern) {
if ( ipStr == null || ipPattern == null) {
return false;
}
String[] patternList = ipPattern.split( ";");
// for(String str : patternList){
// System.out.println("Permissible IP:"+str);
// }
//参数打印测试
for (String pattern : patternList) {
if ( passValidate(ipStr, pattern)) {
return true;
}
}
return false;
}
private static boolean passValidate(String ipStr, String pattern) {
String[] ipStrArr = ipStr.split("\\.");
String[] patternArr = pattern.split("\\.");
if ( ipStrArr. length != 4 || patternArr. length != 4) {
return false;
}
int end = ipStrArr. length;
if ( patternArr[3].contains( "-")) {
end = 3;
String[] rangeArr = patternArr[3].split( "-");
int from = Integer.valueOf(rangeArr[0]).intValue();
int to = Integer.valueOf(rangeArr[1]).intValue();
int value = Integer.valueOf(ipStrArr[3]).intValue();
if ( value < from || value > to) {
return false;
}
}
for ( int i = 0; i < end; i++) {
if ( patternArr[i].equals("*")) {
continue;
}
if (!patternArr[i].equalsIgnoreCase(ipStrArr[i])) {
return false;
}
}
return true;
}
}
配置web.xml,过滤所有.htm的请求:
<!-- IP filter -->
<filter>
<filter-name>IPFilter </filter-name>
<filter-class>com.xiaoniu.auth.filter.IPFilter </filter-class>
<init-param>
<param-name>ip-pattern</param-name>
<param-value> </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>IPFilter </filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
之前在配置时 url-pattern 中使用的是 /*,过滤了所有的请求,包括读取css样式文件等操作,导致错误提示页面变成原始挫页。这里只配置后只过滤了.htm请求,过滤了对核心业务的访问,保留了测试和页面调用的文件。
网友评论