问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/22892223/obtain-the-request-in-resteasy-jax-rs-method