简体   繁体   中英

Apache CXF - share data between In and Out interceptors

I am using Apach CXF as REST provider.

I want to gather data when I enter the webservice, gather data before I enter the resposne and add some calculation to the response. For this question and for simplicity, lets assume I want to get the starting time on entering, the finishing time before the response is sent and add the total time to the response.

Now, how do I do that? I created In and Out interceptors that works fine alone, but how do I use the data from the In interceptor in the Out interceptor?

Thanks Idob



UPDATE:

I tried to set the data as contextual parameter with

message.setContextualProperty(key,value);

but I am getteing NULL on

message.getContextualProperty(key);

I also tried the same but just with

message.put(key,value) and message.get(key)

didn't work.

Idea's anyone?

Thank you, Idob

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM