Apache CXF – 在In和Out拦截器之间共享数据
我使用Apach CXF作为REST提供程序。
我想在进入Web服务时收集数据,在输入resposne之前收集数据并在响应中添加一些计算。 对于这个问题而言,为了简单起见,我们假设我想获得进入的开始时间,发送响应之前的结束时间,并将总时间添加到响应中。
现在,我该怎么做? 我创建了In和Out拦截器,它们可以单独工作,但是如何在Out拦截器中使用In拦截器中的数据呢?
谢谢Idob
更新:
我尝试将数据设置为上下文参数
message.setContextualProperty(key,value);
但我得到的是NULL
message.getContextualProperty(key);
我也尝试了同样但只是
message.put(key,value) and message.get(key)
没用。
想法是谁?
谢谢,Idob
您可以在Exchange
上存储值。 CXF为每个请求创建一个Exchange
对象,以充当请求/响应对的输入和输出消息的容器,并使其可以作为message.getExchange()
从两者中访问。
在拦截器中:
public void handleMessage(Message inMessage) throws Fault { inMessage.getExchange().put("com.example.myKey", myCustomObject); }
拦截器
public void handleMessage(Message outMessage) throws Fault { MyCustomObject obj = (MyCustomObject)outMessage.getExchange().get("com.example.myKey"); }
(反之亦然,对于客户端拦截器,out将存储值,in将检索它们)。 选择一个你知道其他拦截器不会使用的密钥 – 一个包合格的名称是一个不错的选择。 请注意,与Message
类似, Exchange
是一个StringMap
并且具有通用的put / get方法,它将Class
作为键,为您提供编译时类型安全性并节省您必须转换:
theExchange.put(MyCustomObject.class, new MyCustomObject()); MyCustomObject myObj = theExchange.get(MyCustomObject.class);
您的拦截器可以访问javax.xml.ws.handler.MessageContext
。 这扩展了Map
,因此您可以将您想要的任何内容放入上下文中,并在以后的请求中访问它:
public boolean handleMessage(final MessageContext context) { context.put("my-key", myCustomObject); // do whatever else your interceptor does }
稍后的:
public boolean handleMessage(final MessageContext context) { MyCustomObject myCustomObject = context.get("my-key"); // do whatever else your interceptor does }