【发布时间】:2011-02-21 14:44:45
【问题描述】:
如何通过 web.xml 上的一些配置来阻止 IP 地址?
我需要过滤器吗?如何实现?
【问题讨论】:
-
我个人认为这应该在宿主应用服务器的Admin级别或网络级别(防火墙)完成。
标签: java web.xml servlet-filters
如何通过 web.xml 上的一些配置来阻止 IP 地址?
我需要过滤器吗?如何实现?
【问题讨论】:
标签: java web.xml servlet-filters
我通常会使用反向代理网络服务器来实现这一点,但如果你真的想在你的 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(可能从属性甚至数据库):
第
【讨论】:
搞清楚过滤器配置和所有留给读者的练习。
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.xml 中的配置来做到这一点,不。不过,servlet 过滤器是实现这种东西的好地方。
Filter 接口提供 HttpServletRequest 作为过滤器链调用的一部分,您可以从中获取客户端的 IP 地址(使用 getRemoteAddr),并将其与您的允许地址列表进行比较。
或者,您的特定应用服务器可能支持专有级别的 IP 过滤,但这会将您锁定在该容器中(这对您来说可能是也可能不是问题)。
【讨论】:
您不能使用 web.xml 阻止 IP 地址。应该在 Webserver、Container 或 Application Server 级别完成。
如果您使用的是 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
【讨论】: