web.xml配置
<filter>
<filter-name>IPFILTER</filter-name>
<filter-class>com.supconit.ticc3.util.common.IpFilter</filter-class>
</filter>
<!--定义filter拦截的地址-->
<filter-mapping>
<filter-name>IPFILTER</filter-name>
<url-pattern>/datamonitor/founded/*</url-pattern>
</filter-mapping>
自定义过滤器配置
public class IpFilter implements Filter {
private static final Logger logger = Logger.getLogger(IpFilter.class);
private static final Map<String,String> IP_MAP = new HashMap<>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Properties pro = new Properties();
FileInputStream in = null;
try {
String fileName = this.getClass().getClassLoader().getResource("ip_config.properties").getPath();
in = new FileInputStream(fileName);
pro.load(in);
pro.forEach((k, v) -> {
IP_MAP.put((String) k, (String) v);
});
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("初始化过滤器的方法");
logger.info("初始化过滤器的方法");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
String servletPath = req.getServletPath();
logger.info("请求路径过滤信息路径为:" + servletPath);
String ipAddress = findIpAddress(req);
logger.info("请求IP地址为:" + ipAddress);
if(IP_MAP.containsValue(ipAddress)){
chain.doFilter(request,response);
}else{
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter writer = response.getWriter();
Map<String, String> map = new HashMap<>();
map.put("error", "IP没有权限");
writer.write(map.toString());
}
}
@Override
public void destroy() {
System.out.println("结束过滤器的方法");
logger.info("结束过滤器的方法");
}
public static String findIpAddress(HttpServletRequest request){
String ipAddress="";
try {
ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
} catch (Exception e) {
e.printStackTrace();
ipAddress="127:0:0:1";
}
return ipAddress;
}
}