Filter 过滤器学习 , 过滤IP

 

	<!-- 过滤IP -->
     <filter>
         <filter-name>IPFilter</filter-name>
         <filter-class>com.filter.IPFilter</filter-class>
         <init-param>
             <param-name>IPList</param-name>
             <param-value>127.0.0.10,192.1.0.11</param-value>
         </init-param>
         <init-param>
			<param-name>ForbidPath</param-name>
			<param-value>/domeTest2</param-value>
		</init-param>
     </filter>
     <!-- 配置过滤器的映射路径 -->
     <filter-mapping>
         <filter-name>IPFilter</filter-name>
         <url-pattern>/*</url-pattern>
    </filter-mapping>
	
	<!--End 过滤IP -->

 

package com.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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;

public class IPFilter implements Filter{
	private static List<String> ipList = new ArrayList<String>();
	private static String forbidPath = "";//设置权限的路径
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		System.out.println("Init~~~~~~~~~");
		String ips = config.getInitParameter("IPList");
		System.out.println("通行IP"+ips);
		String[] ipArray = ips.split(",");
		if(ipArray != null){
			for(int i = 0; i < ipArray.length; i++){
				ipList.add(ipArray[i]);
			}
		}
		forbidPath = config.getInitParameter("ForbidPath");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("DoFilter~~~~~~~~~");
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		String uri = httpRequest.getRequestURI();
		if(uri.startsWith(forbidPath)){
			String ip = httpRequest.getRemoteAddr();
			System.out.println("来访IP:"+ip);
			if(this.ipList.indexOf(ip) == -1){
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.println("这个IP:【"+ip+"】无访问权限");
				out.flush();
				out.close();
				return;
			}
		}
	}
	
	@Override
	public void destroy() {
		System.out.println("Destroy~~~~~~~~");
	}
}

 

你可能感兴趣的:(filter)