java 版IP白名单
时间: 2023-10-11 12:15:56 浏览: 124
要实现 IP 白名单功能,可以使用 Java 中的过滤器(Filter)。以下是一个简单的 IP 白名单过滤器示例代码:
```java
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class IPFilter implements Filter {
private List<String> whiteList = new ArrayList<>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 读取白名单列表
String ips = filterConfig.getInitParameter("whiteList");
String[] ipArray = ips.split(",");
for (String ip : ipArray) {
whiteList.add(ip.trim());
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String remoteAddr = httpRequest.getRemoteAddr();
if (whiteList.contains(remoteAddr)) {
// IP 在白名单中,放行
chain.doFilter(request, response);
} else {
// IP 不在白名单中,返回 403 Forbidden 状态码
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
public void destroy() {
// do nothing
}
}
```
在 web.xml 中配置过滤器:
```xml
<filter>
<filter-name>IPFilter</filter-name>
<filter-class>com.example.IPFilter</filter-class>
<init-param>
<param-name>whiteList</param-name>
<param-value>127.0.0.1,192.168.0.1</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>IPFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
在 init-param 中配置白名单列表,多个 IP 用逗号分隔。该示例中只是简单的判断 IP 是否在白名单中,实际应用中可以根据需要进行更复杂的判断。
阅读全文