如何通过 web.xml 上的某些配置阻止 IP 地址?
我需要过滤器吗?我该如何实施?
你不能纯粹通过 config in 来做到这一点web.xml
,不。不过,servlet 过滤器是实现这种东西的好地方。
该Filter
接口提供HttpServletRequest
作为过滤器链调用的一部分,您可以从中获取客户端的 IP 地址(使用getRemoteAddr
),并将其与您的允许地址列表进行比较。
或者,您的特定应用服务器可能支持专有级别的 IP 过滤,但这会将您锁定在该容器中(这对您来说可能是也可能不是问题)。
您不能使用 web.xml 阻止 IP 地址。它应该在 Web 服务器、容器或应用程序服务器级别完成。
如果您使用的是 Tomcat,则需要使用 Valve 规范来阻止 IP 地址。可以使用以下资源找到更多信息
http://tomcat.apache.org/tomcat-5.5-doc/config/valve.html
http://hcmc.uvic.ca/blogs/index.php?blog=30&p=2658&more=1&c=1&tb=1&pb=1
弄清楚过滤器配置和所有留给读者的练习。
import javax.servlet.*;
import java.io.IOException;
public class BlackListFilter implements Filter
{
private String blacklistedip;
@Override
public void init(final FilterConfig filterConfig) throws ServletException
{
this.blacklistedip = filterConfig.getInitParameter("blacklistedip");
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) throws IOException, ServletException
{
if (!request.getRemoteAddr().equals(this.blacklistedip))
{
filterChain.doFilter(request, response);
}
}
@Override
public void destroy()
{
// nothing
}
}
我通常会使用反向代理 Web 服务器来实现这一点,但如果你真的想在你的 servlet 中定义它,这不是问题......
下面是一个示例,可指导您使用过滤器进行管理。
http://www.java2s.com/Code/Java/Servlets/IPFilter.htm
请注意,它不包括 web.xml 条目,看起来像这样:
<filter>
<filter-name>IPFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>IPFilter</filter-name>
<servlet-name>MyServlet123</servlet-name>
</filter-mapping>
如果您使用的是 Spring(如上面的过滤器类),您可能希望使用 Spring DelegatingFilterProxy,以简化解决方案,并让您的过滤器访问您的 applicationContext 的其他 bean(可能从属性加载客户端 IP 地址,甚至一个数据库):
hth