allprog
allprog

Reputation: 16790

Obtain the request in Resteasy JAX-RS method

I have a Jax-Rs service that I run with Resteasy, and in the implementation of the methods I want to access the request data. I know of the existence of the @Context annotation but this requires me to modify the service interface which is not practical (or even possible with Java Jax-Rs clients) that use the same interface for client proxy creation.

So to make it cleaner, I have this interface which I can't modify.

@POST
@Path("/ping")
@Consumes({ javax.ws.rs.core.MediaType.APPLICATION_JSON, javax.ws.rs.core.MediaType.APPLICATION_XML })
@Produces({ javax.ws.rs.core.MediaType.APPLICATION_JSON, javax.ws.rs.core.MediaType.APPLICATION_XML })
public String ping();

And in the implementation I want to do something like this (kind of pseudo code)

@Override
public String ping() {
    String client = SomeContextAccessor.getRequest().getRemoteAddress());

    //Use the request info

    return "a nice string";
}

I know there are some classes with static methods that allow me to do this but can't find info about those.

Upvotes: 2

Views: 8399

Answers (1)

allprog
allprog

Reputation: 16790

The solution is a single line:

ResteasyProviderFactory.getContextData(HttpServletRequest.class)

I don't know if injecting this in a field is possible. Method level injection does not work either as I'm using Java clients with the same interface definition. Adding context parameters to a method would screw up this scheme.

Anyway, it works great for me.

Upvotes: 4

Related Questions