要求:
- 本地网络中的每个人都可以访问除 /admin 页面之外的所有页面。
- 只有本地主机可以访问 /admin 页面。
如何为 tomcat 6 或其他替代方案编写 webfilter?
答案1
请在过滤器中使用以下代码来检查请求是否是针对“管理员”:
public static boolean isRequestTo(HttpServletRequest request, String urlPart) {
return request.getRequestURI().startsWith(urlPart);
}
请在过滤器中使用以下代码来检查请求是否来自本地主机:
private static final String LOCAL_IP = "127.0.0.1";
private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";
private static Set<String> localAddresses = new HashSet<String>();
static {
try {
localAddresses.add(InetAddress.getLocalHost().getHostAddress());
for (InetAddress inetAddress : InetAddress.getAllByName("localhost")) {
localAddresses.add(inetAddress.getHostAddress());
}
} catch (Exception e) {
if (!localAddresses.contains(LOCAL_IP)) {
localAddresses.add(LOCAL_IP);
}
if (!localAddresses.contains(LOCAL_IPV6)) {
localAddresses.add(LOCAL_IPV6);
}
}
}
public static boolean isLocalRequest(HttpServletRequest request) {
return localAddresses.contains(request.getRemoteAddr());
}