spring boot對(duì)IP地址設(shè)置黑白名單的項(xiàng)目實(shí)踐
1、在yml配置文件中
ip: whitelist: IP1 #白名單 blacklist: IP2 #黑名單
2、定義過濾器類
@Component
public class IpFilter implements Filter {
//白名單IP列表
private List<String> whitelist;
//黑名單IP列表
private List<String> blacklist;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//獲取上下文信息
ServletContext context = filterConfig.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
Environment environment = ctx.getBean(Environment.class);
//賦予初值
whitelist = Arrays.stream(environment.getProperty("ip.whitelist").split(","))
.map(String::trim)
.collect(Collectors.toList());
blacklist=Arrays.stream(environment.getProperty("ip.blacklist").split(","))
.map(String::trim)
.collect(Collectors.toList());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String ip = httpRequest.getRemoteAddr();
if (whitelist.contains(ip)) {
// 白名單IP,直接通過
chain.doFilter(request, response);
} else if (blacklist.contains(ip)) {
// 黑名單IP,拒絕訪問
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "IP is in blacklist");
} else {
// 非黑白名單IP,根據(jù)業(yè)務(wù)需求處理(例如:允許或拒絕)
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
// 清理資源,如果有的話
}
}
3、注冊(cè)config類FilterConfig
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<IpFilter> ipFilterRegistration() {
FilterRegistrationBean<IpFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new IpFilter());
registrationBean.addUrlPatterns("/*"); // 設(shè)置過濾器攔截的路徑
registrationBean.setName("ipFilter");
registrationBean.setOrder(1); // 設(shè)置過濾器的順序
return registrationBean;
}
}
到此這篇關(guān)于spring boot對(duì)IP地址設(shè)置黑白名單的項(xiàng)目實(shí)踐的文章就介紹到這了,更多相關(guān)springboot IP黑白名單內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏
相關(guān)文章
Mybatis中關(guān)于自定義mapper.xml時(shí),參數(shù)傳遞的方式及寫法
這篇文章主要介紹了Mybatis中關(guān)于自定義mapper.xml時(shí),參數(shù)傳遞的方式及寫法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
JDBC實(shí)現(xiàn)數(shù)據(jù)庫增刪改查功能
這篇文章主要為大家詳細(xì)介紹了JDBC實(shí)現(xiàn)數(shù)據(jù)庫增刪改查功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
Spring中@Repository注解的作用和用法以及和@Mapper的區(qū)別詳析
這篇文章主要給大家介紹了關(guān)于Spring中@Repository注解的作用和用法以及和@Mapper的區(qū)別的相關(guān)資料,注解的作用是標(biāo)識(shí)一個(gè)類為數(shù)據(jù)訪問對(duì)象,并由Spring框架進(jìn)行實(shí)例化和管理,需要的朋友可以參考下2023-09-09
IDEA創(chuàng)建Servlet編寫HelloWorldServlet頁面詳細(xì)教程(圖文并茂)
在學(xué)習(xí)servlet過程中參考的教程是用eclipse完成的,而我在練習(xí)的過程中是使用IDEA的,在創(chuàng)建servlet程序時(shí)遇到了挺多困難,在此記錄一下,這篇文章主要給大家介紹了關(guān)于IDEA創(chuàng)建Servlet編寫HelloWorldServlet頁面詳細(xì)教程的相關(guān)資料,需要的朋友可以參考下2023-10-10

