如何在ContainerRequestFilter中获取远程IP

时间:2014-07-13 15:21:39

标签: java rest jersey

我有这个课,想要记录其余的请求:

public class RequestFilter implements ContainerRequestFilter {

    private static final Logger LOG = LoggerFactory.getLogger(RequestFilter.class);

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        LOG.info("REST-Request from '{}' for '{}'", "XXX", requestContext.getUriInfo().getPath());
        // ... and do some auth stuff (not relevant for this question)
    }
}

如何获取请求的远程IP? TIA!

2 个答案:

答案 0 :(得分:9)

试试这个:

public class RequestFilter implements ContainerRequestFilter {

    private static final Logger LOG = LoggerFactory.getLogger(RequestFilter.class);

    @Context
    private HttpServletRequest request;

    // rest of your stuff here

答案 1 :(得分:3)

迟到的回复,但这可能会帮助其他人使用Grizzly2 ......

import javax.servlet.http.HttpServletRequest;
import org.glassfish.grizzly.http.server.Request;

public class RequestFilter implements ContainerRequestFilter {

    private static final Logger LOG = LoggerFactory.getLogger(RequestFilter.class);

    @Context
    private HttpServletRequest httpServletRequest;

    @Inject
    private Provider<Request> grizzlyRequest;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String remoteIpAddress;
        if (httpServletRequest != null) {
            // JSR-315/JSR-339 compliant server
            remoteIpAddress = httpServletRequest.getRemoteAddr();
        } else {
            // Grizzly2 server
            remoteIpAddress = grizzlyRequest.get().getRemoteAddr();
        }