JAVA中IP地址拦截的处理
程序员文章站
2022-07-02 14:29:37
...
//IP地址拦截,在web.xml中的配置
<!-- ip filter -->
<filter>
<filter-name>setIpByIpFilter</filter-name> //拦截器的名称自己设置
<filter-class>com.rbt.filter.BanIpFilter</filter-class> //启用拦截器的Action类
</filter>
<filter-mapping>
<filter-name>setIpByIpFilter</filter-name> //拦截器的的名称,跟上面的名称是相同
<url-pattern>/*</url-pattern> //要拦截的页面,*表示所有请求的页面都进行拦截
</filter-mapping>
//IP拦截器处理的Action类
public class BanIpFilter extends CreateSpringContext implements Filter
{
/*
* 方法描述:提供IP拦截的方法
*/
public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws ServletException, IOException
{
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String requestIp = request.getRemoteAddr();
String requestUrl = request.getRequestURL().toString();
String toUrl = "/include/IpLimit.jsp";//跳转到限制IP提示页面
Map pageMap = new HashMap();
if(requestIp!=null && !requestIp.equals(""))
pageMap.put("ip", requestIp);
IBan_IpService ban_ipService = (IBan_IpService)getContext().getBean("ban_ipService");//获取数据库的IP地址
int count = ban_ipService.getBanIpCount(pageMap);//数据库查询IP是否在数据库中。如果count=0就跳过拦截,否则就进行拦截;
if(count!=0 && requestUrl.indexOf(toUrl) == -1)//匹配数据库限制IP
{
response.sendRedirect(toUrl);//直接跳转到拦截页面
}
else
{
chain.doFilter(req, resp);//跳过拦截
}
}
}
<!-- ip filter -->
<filter>
<filter-name>setIpByIpFilter</filter-name> //拦截器的名称自己设置
<filter-class>com.rbt.filter.BanIpFilter</filter-class> //启用拦截器的Action类
</filter>
<filter-mapping>
<filter-name>setIpByIpFilter</filter-name> //拦截器的的名称,跟上面的名称是相同
<url-pattern>/*</url-pattern> //要拦截的页面,*表示所有请求的页面都进行拦截
</filter-mapping>
//IP拦截器处理的Action类
public class BanIpFilter extends CreateSpringContext implements Filter
{
/*
* 方法描述:提供IP拦截的方法
*/
public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws ServletException, IOException
{
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String requestIp = request.getRemoteAddr();
String requestUrl = request.getRequestURL().toString();
String toUrl = "/include/IpLimit.jsp";//跳转到限制IP提示页面
Map pageMap = new HashMap();
if(requestIp!=null && !requestIp.equals(""))
pageMap.put("ip", requestIp);
IBan_IpService ban_ipService = (IBan_IpService)getContext().getBean("ban_ipService");//获取数据库的IP地址
int count = ban_ipService.getBanIpCount(pageMap);//数据库查询IP是否在数据库中。如果count=0就跳过拦截,否则就进行拦截;
if(count!=0 && requestUrl.indexOf(toUrl) == -1)//匹配数据库限制IP
{
response.sendRedirect(toUrl);//直接跳转到拦截页面
}
else
{
chain.doFilter(req, resp);//跳过拦截
}
}
}