我正在使用Apach CXF作为REST提供程序。
我想在进入 Web 服务时收集数据,在输入响应之前收集数据,并在响应中添加一些计算。为了这个问题和简单起见,假设我想获取输入的开始时间,发送响应之前的完成时间,并将总时间添加到响应中。
现在,我该怎么做?我创建了单独工作的 In 和 Out 拦截器,但我如何使用 In 拦截器中的数据?
谢谢伊多布
更新:
我尝试将数据设置为上下文参数
message.setContextualProperty(key,value);
但我正在为空
message.getContextualProperty(key);
我也尝试了相同的方法,但只是
message.put(key,value) and message.get(key)
没用。
想法是任何人吗?
谢谢伊多布
您可以将值存储在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
,并且具有以Class
为键的通用 put/get 方法,这些方法为您提供编译时类型安全性并节省您不必强制转换:
theExchange.put(MyCustomObject.class, new MyCustomObject());
MyCustomObject myObj = theExchange.get(MyCustomObject.class);
您的拦截器可以访问javax.xml.ws.handler.MessageContext
。这扩展了Map<String,Object>
,因此您可以将所需的任何内容放入上下文中,并在请求的稍后访问它:
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
}