Obtain the request in Resteasy JAX-RS method

夙愿已清 提交于 2021-01-28 19:21:11

问题


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

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