![服务器 localhost 来访问 /admin/* 页面并阻止所有其他页面](https://linux22.com/image/609220/%E6%9C%8D%E5%8A%A1%E5%99%A8%20localhost%20%E6%9D%A5%E8%AE%BF%E9%97%AE%20%2Fadmin%2F*%20%E9%A1%B5%E9%9D%A2%E5%B9%B6%E9%98%BB%E6%AD%A2%E6%89%80%E6%9C%89%E5%85%B6%E4%BB%96%E9%A1%B5%E9%9D%A2.png)
要求:
- 本地网络中的每个人都可以访问除 /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());
}