How to get the remote IP in a ContainerRequestFilter

ぐ巨炮叔叔 提交于 2019-12-11 02:46:59

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/24724190/how-to-get-the-remote-ip-in-a-containerrequestfilter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!