request请求中通过过滤获取准确IP地址
程序员文章站
2022-07-10 17:35:40
...
@Service
public class WebserviceFilter extends HttpServlet implements Filter{
private static final long serialVersionUID = -4581179717286075213L;
private IConfigurationInfoService configurationInfoService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
/**
* 过滤请求IP
* @param ServletRequest
* @param ServletResponse
* @param FilterChain
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 使用x-forwarded-for或Proxy-Client-IP或WL-Proxy-Client-IP得到ip地址
String ipString = request.getHeader("x-forwarded-for");
if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
ipString = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
ipString = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
// 若以上三种方式均为获取到ip则证明获得客户端并没有采用反向代理直接使用getRemoteAddr()获取客户端的ip地址
ipString = request.getRemoteAddr();
}
// 多个路由时,取第一个非unknown的ip
final String[] arr = ipString.split(",");
for (final String str : arr) {
if (!"unknown".equalsIgnoreCase(str)) {
ipString = str;
break;
}
}
// 使用WebApplicationUtils获取ConfigurationService
ServletContext sc = ((HttpServletRequest) req).getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("configurationInfoService") != null && configurationInfoService == null){
configurationInfoService = (IConfigurationInfoService) cxt.getBean("configurationInfoService");
}
// 根据分类编号与查询编号获取IP
String configurationValue = configurationInfoService
.getConfigurationValueByConFigCode(
OperatingIndexConstants.CONFIGURATION_CODE,
OperatingIndexConstants.CATEGORY_CODE);
// 判断是否有匹配的IPAddress,如果有匹配的 放行
if(StringUtils.isNotBlank(configurationValue) && configurationValue.indexOf(ipString) >= 0){
chain.doFilter(request, response);
}
}
}