标签:
示例:创建一个IP过滤Filter,当一个用户发出访问请求的时候,首先通过过滤器进行判断,
如果用户的IP地址被限制,就禁止访问,只有合法的IP才可以继续访问。IP过滤Filter代码如下:
IPFilter.java
1 package com.mhb; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.Filter; 7 import javax.servlet.FilterChain; 8 import javax.servlet.FilterConfig; 9 import javax.servlet.ServletException; 10 import javax.servlet.ServletRequest; 11 import javax.servlet.ServletResponse; 12 13 public class IPFilter implements Filter { 14 15 protected FilterConfig filterConfig; 16 protected String ip; 17 18 public void init(FilterConfig filterConfig) throws ServletException { 19 this.filterConfig = filterConfig; //设置属性filterConfig 20 this.ip = this.filterConfig.getInitParameter("ip"); //设置初始化参数IP 21 } 22 //过滤方法 23 public void doFilter(ServletRequest request, ServletResponse response, 24 FilterChain chain) throws IOException, ServletException { 25 String remoteIP = request.getLocalAddr(); //获得客户端ip地址 26 27 if(remoteIP.equals(ip)){ //判断IP是否被禁止 28 response.setCharacterEncoding("gb2312"); //设置输出内容编码格式 29 PrintWriter out = response.getWriter(); 30 out.println("<b>你的IP地址被禁止访问!</b>"); 31 }else{ 32 chain.doFilter(request, response); 33 } 34 } 35 //销毁方法 36 public void destroy() { 37 } 38 }
web.xml配置
<filter> <filter-name>IPFilter</filter-name> <filter-class>com.mhb.IPFilter</filter-class> <init-param> <param-name>ip</param-name> <param-value>127.0.0.1</param-value> </init-param> </filter> <filter-mapping> <filter-name>IPFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
浏览器显示:
标签:
原文地址:http://www.cnblogs.com/tdcqma/p/4760434.html