某些时候 我们并不希望有些特定的用户访问我们的网站 但在下面的过滤器中 需要建立在你知道对方的IP地址的同时
下面介绍了一个简单的Ip地址过滤器 包括过滤器类的编写和 web.xml的配置
1.适配器模式 (让适配器类空实现适配器接口 ):
package com.Jeelon.FilterAdapter; 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; public class IpFilterAdapter implements Filter { public void destroy() { } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { } public void init(FilterConfig arg0) throws ServletException { } }
2.过滤器类 它继承至过滤器适配器并且实现其中关键方法:
package com.Jeelon.ipFilter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.Jeelon.FilterAdapter.IpFilterAdapter; public class IpFilter extends IpFilterAdapter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request1 = (HttpServletRequest)request; HttpServletResponse response1 = (HttpServletResponse)response; //获得客户端的IP地址 String ip = request.getRemoteAddr() + ""; System.out.println(ip); //以转义字符//对.进行转义 拆分 一般用,- | 用的比较多 用.就回出错 需要用转义字符转义 /* ips[0] = 192 ips[1] = 168 ips[2] = 2 ips[3] = 47 */ String ips[] = ip.split("//."); //192.168.0.1 int ad = Integer.parseInt(ips[3]); /* * 以上拆分方法还可以用以下代替: * int ad = Integer.parseInt(ip.substring(ip.lastIndexOf(".") + 1)); */ if(ad >= 1 && ad <= 50){ /*response.setContentType("text/html;charset=utf-8"); response.getWriter().print("您没有权限访问");*/ request1.getRequestDispatcher("error.jsp").forward(request1, response1); } else{ chain.doFilter(request, response); } } }
3.web.xml的配置 :
<filter> <filter-name>IPFilter</filter-name> <filter-class>com.Jeelon.ipFilter.IpFilter</filter-class> </filter> <filter-mapping> <filter-name>IPFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
这样 一个简单的Ip地址过滤器就产生了,在我们知道对方Ip的情况下 就可以阻止对方的访问!!