IP过滤DEMO

import java.io.IOException;
import java.io.PrintWriter;

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 IPFilter implements Filter {
	
	FilterConfig fc = null;
	
	public void destroy() {
		System.out.println("IPFilter destroy");
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		String ip = req.getRemoteAddr();
		String strIPBlackList = fc.getInitParameter("IPBlackList");
		if(strIPBlackList.indexOf(ip) != -1) {
			PrintWriter out = resp.getWriter();
			out.println("Your IP is not welcome!");
			return;
		}
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig fc) throws ServletException {
		System.out.println("IPFilter init");
		this.fc = fc;
	}

}

 web.xml中的配置:

	<filter>
		<filter-name>IPFilter</filter-name>
		<filter-class>
			com.bjsxt.shopping.util.filter.IPFilter
		</filter-class>
		<init-param>
			<param-name>IPBlackList</param-name>
			<param-value>192.168.0.10,192.168.0.11</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>IPFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

你可能感兴趣的:(Web,xml,servlet)