Apache CXF - share data between In and Out interceptors
You can store values on the Exchange
. CXF creates an Exchange
object for each request to act as a container for the in and out messages for the request/response pair and makes it accessible as message.getExchange()
from both.
In interceptor:
public void handleMessage(Message inMessage) throws Fault {
inMessage.getExchange().put("com.example.myKey", myCustomObject);
}
Out interceptor
public void handleMessage(Message outMessage) throws Fault {
MyCustomObject obj = (MyCustomObject)outMessage.getExchange().get("com.example.myKey");
}
(or vice-versa for client-side interceptors, where the out would store values and the in would retrieve them). Choose a key that you know won't be used by other interceptors - a package-qualified name is a good choice. Note that, like Message
, Exchange
is a StringMap
and has generic put/get methods taking a Class
as the key that give you compile-time type safety and save you having to cast:
theExchange.put(MyCustomObject.class, new MyCustomObject());
MyCustomObject myObj = theExchange.get(MyCustomObject.class);
Your interceptors have access to javax.xml.ws.handler.MessageContext
. This extends Map<String,Object>
, so you can put whatever you want into the context and access it later on in the request:
public boolean handleMessage(final MessageContext context) {
context.put("my-key", myCustomObject);
// do whatever else your interceptor does
}
Later on:
public boolean handleMessage(final MessageContext context) {
MyCustomObject myCustomObject = context.get("my-key");
// do whatever else your interceptor does
}