Binh Tran
Binh Tran

Reputation: 133

How to get source address / ip from inside ContainerResponseFilter

I'm writing a logging filter that logs all HTTP requests / responses for a web app running in Jersey. ContainerResponseFilter seems to a straight forward solution and I've managed to get it to work.

Next step is to log the IP of the requests. Is there a way to do that from inside the ContainerResponseFilter ?

Upvotes: 3

Views: 8370

Answers (1)

zyexal
zyexal

Reputation: 1579

Short answer:

@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 the wish for a more detailed answer)

Afaig:

The @Context annotation allows to inject JAX-RS–specific components (one might say you are able to inject contextual information objects). JAX-RS itself is a Java based specification for RESTful Web Services over HTTP protocol. So we are able to inject stuff like:

javax.ws.rs.core.UriInfo
javax.ws.rs.core.Request
javax.ws.rs.core.SecurityContext

and also
javax.servlet.http.HttpServletRequest

In the IOC Chapter of the Jersey docs, you will find these notes:

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

[...] The exception exists for specific request objects which can injected even into constructor or class fields. For these objects the runtime will inject proxies which are able to simultaneously server more request. These request objects are HttpHeaders, Request, UriInfo, SecurityContext. These proxies can be injected using the @Context annotation. [...]

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

And if you do so, you inject in fact a Proxy named org.apache.catalina.connector.RequestFacade (link). This proxy functioned as your direct hotline to your Coyote (HTTP Connector) and thereby to the Coyote request object (link).

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

Upvotes: 13

Related Questions