/**
*
*/
package com.ambow.servlet.day4;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//字符串解析
import java.util.StringTokenizer;
/**
* 检查并阻塞特定的 IP
* 阻止 192.168 开头的 ip 地址访问某个资源
*
* @author Administrator
*
*/
public class Filter6 implements Filter {
//指定要被屏蔽 的 ip
private final static String IP_RANGE="192.168";
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
//转换 Request 对象
HttpServletResponse res = null;
//通过请求对象,得到客户端 ip 地址
String ip = arg0.getRemoteAddr();
System.out.println("客户端 ip ="+ip);
if(arg1 instanceof HttpServletRequest)
{
res = (HttpServletResponse)arg1;
}
//将 ip 地址分解
//127.0.0.1 ==> 127 0 0 1
StringTokenizer toke = new StringTokenizer(ip,".");
int dots = 0;
String byte1="";
String byte2="";
String client="";
while(toke.hasMoreTokens())
{
++dots;
//如果是第一个 ip
if(dots == 1)
{
byte1 = toke.nextToken();
}else {
byte2 = toke.nextToken();
//只关心前两个字节
break;
}
}
//将客户 ip 拼起来
client = byte1+"."+byte2;
//如果 ip 在被禁止的范围内
if(this.IP_RANGE.equals(client))
{
System.out.println("该 ip 被禁止访问 :"+client);
//403 禁止访问
res.sendError(HttpServletResponse.SC_FORBIDDEN,"GoodBye Forever!");
}else
{
System.out.println("该 ip 可以访问 :"+client);
arg2.doFilter(arg0, arg1);
}
}
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}