Create a Filter class that implements javax.servlet.Filter
, and fetch the IP from ServletRequest
using getRemoteAddr()
:
public final class ExtractIpFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String ip = request.getRemoteAddr();
// do something with the IP
}
}
If your client is behind a proxy, try using request.getHeader("x-forwarded-for")
instead, though this may or may not work depending on the configuration of the proxy.