자바 웹 이 접근 하 는 IP 를 어떻게 제한 하 는 지 상세 하 게 설명 하 는 두 가지 방법

15176 단어 Java접근 제한IP
얼마 전에 프로젝트 를 하 다가 이 기능 을 만 났 기 때문에 지금 잘 정리 해 보 세 요.왜 IP 방문 을 제한 하 는 지 에 대해 서 는 더 이상 말 하지 않 겠 습 니 다.그리고 바 이 두 는 현재 IP 접근 을 제한 하 는 두 가지 방법 이 있 습 니 다.첫 번 째 는 가장 간단 하고 편리 합 니 다.두 번 째 는 필 터 를 통 해 접근 을 제한 하 는 것 입 니 다.다음은 제 가 첫 번 째 방식 을 간단하게 소개 하고 두 번 째 방식 을 중점적으로 소개 하 겠 습 니 다.
첫 번 째 방식(Tomcat 설정 설정 에서 IP 접근 허용 또는 제한)
이것 은 가장 간단 하고 빠 른 것 으로 주로 Tomcat 의 server.xml 설정 과 관련된다.
첫 번 째 단계:server.xml 파일 이 어디 에 있 는 지,Tomcat 디 렉 터 리 에 있 는 conf 폴 더 에 있 는 지 찾 습 니 다.
두 번 째 단계:server.xml 파일 을 열 고 Host 노드 를 찾 습 니 다.

<Valve className="org.apache.catalina.valves.RemoteAddrValve" 
	allow="127.0.0.1" 
	deny=""/>
그 중:
className:자바 클래스 이름 을 표시 합 니 다.
org.apache.catalina.valves.RemoteHostValve 또는 org.apache.catalina.valves.RemoteAddrValve;
allow:허용 되 는 IP 를 표시 합 니 다.모호(*),정규,여러 개 사용,분리 지원 합 니 다.
deny:제 한 된 IP 를 표시 하고 모호(*),정규 지원 합 니 다.여러 개 로 나누다.
주:특정한 사이트(사이트)를 제한 하 는 경우 Context 노드 에 추가 합 니 다.
세 번 째 단계:Tomcat 를 다시 시작 합 니 다.
두 번 째 방식(필터 필 터 를 통 해 IP 접근 허용 또는 제한 설정)
(1)코드 실현 의 사고
*8195:8195:프로필 properties 를 추가 하여 접근 할 수 있 는 IP 를 일정한 규칙 에 따라 설정 합 니 다.다음 에 프로필(여 기 는 프로필 이 라 고도 함)을 불 러 옵 니 다.그리고 프로필 의 형식 을 정규 로 검사 해 야 합 니 다.그 다음 에 설 정 된 IP 를 하나의 집합 을 통 해 수집 하면 하나의 IP 나 하나의 IP 의 정규 를 수집 할 수 있 습 니 다.왜냐하면 우 리 는 모호 함 을 사용 해 야 하기 때 문 입 니 다.마지막 으로 방문 자의 IP 와 집합 중의 것 을 비교 하고 통과 하 는 것 보다 정상 적 인 방문 을 한다.그렇지 않 으 면.반대로
설정 파일 에서 가장 흔히 볼 수 있 는 세 가지 IP 설정 방식 을 제공 합 니 다.
하나의 IP 주소 설정,여러 개의 사 이 를 쉼표 로 나 누 거나 분리 합 니 다.
예 를 들 어 192.168.1.50;127.0.0.1;IP 주소 구간 방식 의 설정 으로 여러 구간 을 쉼표 로 나 누 거나 분리 합 니 다.
예 를 들 어 172.2.032.10-172.2.032.11;172.2.032.88-172.2.032.89 어댑터 로 여러 개 를 쉼표 로 나 누 거나 분리 합 니 다.
예 를 들 어 172.20.30.*
(2)구체 적 인 실현 코드
첫 번 째 단계:설정 파일/test/src/com/config/ipConfig.properties 를 작성 합 니 다.

#  IP     ,            
allowIP=192.168.1.50;127.0.0.1;

#IP         ,            
allowIPRange=172.20.32.10-172.20.32.11;172.20.32.88-172.20.32.89

#   ,          
allowIPWildcard=172.20.30.*;
두 번 째 단계:새로운 자바 클래스 가 Filter 를 실현 합 니 다.
세 번 째 단계:웹.xml 에 필 터 를 설정 합 니 다.

<!--     -->
 
 <!-- ip   ,         -->
 <filter>
 	<filter-name>IPFilter</filter-name>
 	<filter-class>com.filter.IpFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>IPFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <!--       -->
네 번 째 단계:접근 할 수 있 는 IP 나 정규 식 을 저장 하기 위해 전역 변수 List 를 설명해 야 합 니 다.

//     :
//         ip
private List<String> allowList = new ArrayList<String>();
다섯 번 째 단계:설정 파일 을 불 러 와 야 합 니 다.방법 init 에서

//     :
//       
InputStream inputStream = IpFilter.class.getResourceAsStream("../config/ipConfig.properties");
		
Properties properties = new Properties();
		
//  Properties       
properties.load(inputStream);
		
//          
String allowIP = properties.getProperty("allowIP");
String allowIPRange = properties.getProperty("allowIPRange");
String allowIPWildcard = properties.getProperty("allowIPWildcard");
여섯 번 째 단계:설정 파일 형식 검사 하기;방법 init 에서

//       
//    ,         ,    
if(allow == null || "".equals(allow.trim())) {
	return true;
} else {
	//      , ;    
	if(!allow.endsWith(";") && !allow.endsWith(",")) {
		allow += ";";
	}
	//    ,   true
	if(pattern.matcher(allow).matches()) {
		return true;
	}
}
STEP 7:각 설정 방식 의 IP 가 져 오기;방법 init 에서

/*
 *            allowList 
 */
//          allowList 
if(null != allowIP && !"".equals(allowIP.trim())) {
	String[] allowIPs = allowIP.split(",|;");
	for(String ip : allowIPs) {
		allowList.add(ip);
	}
}

//          allowList 
if(null != allowIPRange && 
		!"".equals(allowIPRange.trim())) {
	//         
	String[] allowIPRanges = allowIPRange.split(",|;");
	
	if(allowIPRanges.length > 0) {
		//        
		for(String allowRanges : allowIPRanges) {
			if(allowRanges != null && 
					!"".equals(allowRanges.trim())) {
				//    ip    
				String[] ips = allowRanges.split("-");
				if(ips.length > 0 && ips.length < 3) {
					String from = ips[0];//       ip
					String to = ips[1]; //       ip
					
					//   ip       ,        ip      
					String share = from.substring(0, from.lastIndexOf(".")+1);
					
					//   ip    ip     
					int start = Integer.parseInt(from.substring(from.lastIndexOf(".")+1, 
														from.length()));
					//   ip    ip     
					int end = Integer.parseInt(to.substring(to.lastIndexOf(".")+1, 
														to.length()));
					for(int i=start; i<=end; i++) {
						String ip = share + String.valueOf(i);
						allowList.add(ip);
					}
				} else {
					throw new RuntimeException("      ,   !");
				}
			}
			
		}
	}
	
}

//          allowList 
if(allowIPWildcard != null && 
		!"".equals(allowIPWildcard)) {
	//         ip  
	String[] allowIPWildcards = allowIPWildcard.split(",|;");
	
	if(allowIPWildcards.length > 0) {
		for(String ip : allowIPWildcards) {
			if(ip.indexOf("*") != -1) {
				// *    
				ip = ip.replaceAll("\\*", "(25[0-5]|2[0-4]\\\\d|[0-1]\\\\d{2}|[1-9]?\\\\d)");
				
				allowList.add(ip);
			} else {
				throw new RuntimeException("      ,   !");
			}
			
		}
		
	}
}
여덟 번 째 단계:IP 비교,일치 하면 정상적으로 접근 하고,반대로 오류 페이지 로 이동 합 니 다.이것 은 사용자 가 방문 할 때 만 진행 되 는 절차 이기 때문에 doFilter 방법 으로 작성 해 야 합 니 다.

//     IP  
String remoteAddr = request.getRemoteAddr();
//System.out.println("===============" + remoteAddr);
//  allowList  ,       ,          
if(allowList.size() == 0 || allowList == null) {
	filterChain.doFilter(request, response);
} else {
	Boolean flag = false; //    ,   false,    
	//      
	for(String regex : allowList){
		if(remoteAddr.matches(regex)){
			//ip    ,    
			filterChain.doFilter(request, response);
			flag = true; //  true,       
			break;
		}
	}
	if(!flag) {
		//ip   ,      
		request.getRequestDispatcher("WEB-INF/success/error.jsp").forward(request, response);
	}
}
첨부 성공 후 캡 처:
访问成功
访问失败
전체 코드 첨부:

package com.filter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *    
 *   :    IP      
 * @author ouyang
 * @serial 20180728
 * @version 1.0
 */
public class IpFilter implements Filter{

	//         ip
	private List<String> allowList = new ArrayList<String>();
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		try {
			System.out.println("   IpFilter     ,  :IP    ");
			initConfig();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		
		//     IP  
		String remoteAddr = request.getRemoteAddr();
		//System.out.println("===============" + remoteAddr);
		//  allowList  ,       ,          
		if(allowList.size() == 0 || allowList == null) {
			filterChain.doFilter(request, response);
		} else {
			Boolean flag = false; //    ,   false,    
			//      
			for(String regex : allowList){
				if(remoteAddr.matches(regex)){
					//ip    ,    
					filterChain.doFilter(request, response);
					flag = true; //  true,       
					break;
				}
			}
			if(!flag) {
				//ip   ,      
				request.getRequestDispatcher("WEB-INF/success/error.jsp").forward(request, response);
			}
		}
		
	}
	
	@Override
	public void destroy() {
		System.out.println("   IpFilter  。");
	}

	/**
	 *              
	 * @author   
	 * @serialData 20180728
	 * @throws IOException
	 */
	public void initConfig() throws IOException {
		//       
		InputStream inputStream = IpFilter.class.getResourceAsStream("../config/ipConfig.properties");
		
		Properties properties = new Properties();
		
		//  Properties       
		properties.load(inputStream);
		
		//          
		String allowIP = properties.getProperty("allowIP");
		String allowIPRange = properties.getProperty("allowIPRange");
		String allowIPWildcard = properties.getProperty("allowIPWildcard");
		
		//  ,         
		if(!validate(allowIP, allowIPRange, allowIPWildcard)) {
			throw new RuntimeException("      ,   !");
		}
		
		/*
		 *            allowList 
		 */
		//          allowList 
		if(null != allowIP && !"".equals(allowIP.trim())) {
			String[] allowIPs = allowIP.split(",|;");
			for(String ip : allowIPs) {
				allowList.add(ip);
			}
		}
		
		//          allowList 
		if(null != allowIPRange && 
				!"".equals(allowIPRange.trim())) {
			//         
			String[] allowIPRanges = allowIPRange.split(",|;");
			
			if(allowIPRanges.length > 0) {
				//        
				for(String allowRanges : allowIPRanges) {
					if(allowRanges != null && 
							!"".equals(allowRanges.trim())) {
						//    ip    
						String[] ips = allowRanges.split("-");
						if(ips.length > 0 && ips.length < 3) {
							String from = ips[0];//       ip
							String to = ips[1]; //       ip
							
							//   ip       ,        ip      
							String share = from.substring(0, from.lastIndexOf(".")+1);
							
							//   ip    ip     
							int start = Integer.parseInt(from.substring(from.lastIndexOf(".")+1, 
																from.length()));
							//   ip    ip     
							int end = Integer.parseInt(to.substring(to.lastIndexOf(".")+1, 
																to.length()));
							for(int i=start; i<=end; i++) {
								String ip = share + String.valueOf(i);
								allowList.add(ip);
							}
						} else {
							throw new RuntimeException("      ,   !");
						}
					}
					
				}
			}
			
		}
		
		//          allowList 
		if(allowIPWildcard != null && 
				!"".equals(allowIPWildcard)) {
			//         ip  
			String[] allowIPWildcards = allowIPWildcard.split(",|;");
			
			if(allowIPWildcards.length > 0) {
				for(String ip : allowIPWildcards) {
					if(ip.indexOf("*") != -1) {
						// *    
						ip = ip.replaceAll("\\*", "(25[0-5]|2[0-4]\\\\d|[0-1]\\\\d{2}|[1-9]?\\\\d)");
						
						allowList.add(ip);
					} else {
						throw new RuntimeException("      ,   !");
					}
					
				}
				
			}
		}
		
		//    allowList
		for(String str : allowList) {
			System.out.println(str);
		}
		
	}
	
	/**
	 *          
	 * @author ouyang
	 * @serialData 20180728
	 * @param allowIP
	 * @param allowIPRange
	 * @param allowIPWildcard
	 * @return
	 */
	public Boolean validate(String allowIP, String allowIPRange, String allowIPWildcard) {
		Boolean result = false;
		//IP        
		String regx = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
		//  ip   
		String ipRegx = regx + "\\." + regx + "\\."+ regx + "\\." + regx;
		
		//          
		Pattern pattern = Pattern.compile("("+ipRegx+")|("+ipRegx+"(,|;))*");
		if(this.isNullorMatches(allowIP, pattern)){
			result = true; //    
		} else {
			result = false;
		}
		
		//          
		pattern = Pattern.compile("("+ipRegx+")\\-("+ipRegx+")|" + 
						"(("+ipRegx+")\\-("+ipRegx+")(,|;))*");
		if(this.isNullorMatches(allowIPRange, pattern)){
			result = true; //    
		} else {
			result = false;
		}
		
		//          
		pattern = Pattern.compile("("+regx+"\\."+ regx+"\\."+regx+"\\."+ "\\*)|" + 
						"("+regx+"\\."+regx+"\\."+regx+"\\."+ "\\*(,|;))*");
		if(this.isNullorMatches(allowIPWildcard, pattern)){
			result = true; //    
		} else {
			result = false;
		}
		
		return result;
	}
	
	/**
	 *       
	 * @author   
	 * @serialData 20180728
	 * @param allow
	 * @return
	 */
	public Boolean isNullorMatches(String allow, Pattern pattern) {
		//    ,         ,    
		if(allow == null || "".equals(allow.trim())) {
			return true;
		} else {
			//      , ;    
			if(!allow.endsWith(";") && !allow.endsWith(",")) {
				allow += ";";
			}
			//    ,   true
			if(pattern.matcher(allow).matches()) {
				return true;
			}
		}
		
		return false;
	}
}
자바 웹 이 접근 을 제한 하 는 IP 를 어떻게 제한 하 는 지 에 관 한 두 가지 방법 에 관 한 글 을 소개 합 니 다.더 많은 자바 접근 제한 IP 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!

좋은 웹페이지 즐겨찾기