How to get source / ip address from inside ContainerResponseFilter

I am writing a registration filter that logs all HTTP requests / responses for a web application running in Jersey. ContainerResponseFilter

seems like a straight forward solution and I managed to get it to work.

The next step is to register the IP address of the requests. Is there a way to do this internally ContainerResponseFilter

?

+3


source to share


1 answer


The short answer is:

@Provider
public class YourContextFilter implements ContainerRequestFilter {

    @Context
    private HttpServletRequest sr;

    @Override
    public synchronized void filter(ContainerRequestContext request) throws IOException {
        /*
         * Returns the Internet Protocol (IP) address of the client or 
         * last proxy that sent the request. For HTTP servlets, same as 
         * the value of the CGI variable REMOTE_ADDR.
         */
        String ip = sr.getRemoteAddr();
        // ... log it ...
    }

}

      


EDIT
(regarding wanting a more detailed answer)

Afaig:

Annotation @Context

allows you to inject JAX-RS- specific components (you could say that you can inject objects of contextual information). JAX-RS itself is a Java specification for RESTful Web Services over HTTP. This way we can inject things like:



javax.ws.rs.core.UriInfo


javax.ws.rs.core.Request


javax.ws.rs.core.SecurityContext


and javax.servlet.http.HttpServletRequest

In the IOC chapter in the Jersey docs, you will find the following notes:

[...] Jersey's implementation allows you to directly inject an HttpServletRequest instance into JAX-RS components [...] - https://jersey.java.net/nonav/documentation/latest/user-guide.html#d0e2401

[...] An exception exists for specific query objects that can even be injected into the fields of a constructor or class. For these objects, the runtime will inject proxies that can make more requests at the same time. These request objects are HttpHeaders, Request, UriInfo, SecurityContext. These proxies can be injected using the @Context annotation. [...]

[...] When deploying a JAX-RS application that uses a Servlet, ServletConfig, ServletContext, HttpServletRequest, and HttpServletResponse are available using @Context. [...]

And if you do, you are actually entering a proxy named org.apache.catalina.connector.RequestFacade

( link ). This proxy functioned as your direct hotline for your Coyote (HTTP Connector) and therefore for the Coyote request object ( link ).

Hope it was helpful somehow :) - Have a nice day.

+11


source