자바 웹 이 접근 하 는 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 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.