简体   繁体   中英

How to get the remote IP in a ContainerRequestFilter

I have this class and wants to log the rest-requests:

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)
    }
}

How do do I get the remote IP of the request? TIA!

Try this:

public class RequestFilter implements ContainerRequestFilter {

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

    @Context
    private HttpServletRequest request;

    // rest of your stuff here

A late reply, but this may help others using 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();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM