在Resteasy JAX-RS方法中获取请求 [英] Obtain the request in Resteasy JAX-RS method
问题描述
我有一个与Resteasy一起运行的Jax-Rs服务,并且在方法的实现中,我想访问请求数据.我知道 @Context 注释的存在,但这需要我修改了使用同一接口进行客户端代理创建的不实际的服务接口(甚至对于Java Jax-Rs客户端也是可能的).
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.
推荐答案
解决方案仅需一行:
ResteasyProviderFactory.getContextData(HttpServletRequest.class)
我不知道是否可以将其注入字段中.方法级别注入也不起作用,因为我正在使用具有相同接口定义的Java客户端.在方法中添加上下文参数会搞砸这种方案.
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.
这篇关于在Resteasy JAX-RS方法中获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!