Interceptors are the fundamental processing unit which is native in Apache CXF. Basically they are Java classes that intercept your message to provide or apply certain core services to it. In this tutorial we will show how to use them and how to create some custom ones.
Apache CXF provides many built-in Interceptors that provide core services to the message that is being exchanged between consumer and service endpoint. These interceptors do the work of marshalling and unmarshalling, manipulating message headers, performing authorization checks, validating the message data, and so on.
You can also create your own Interceptors which are able to process incoming and outgoing messages. However before that, you need to learn how Interceptors work:
Interceptors are invoked in chain and organized in phases. When a CXF client invokes a CXF server, there is an outgoing interceptor chain for the client and an incoming chain for the server. When the server sends the response back to the client, there is an outgoing chain for the server and an incoming one for the client. Additionally, in the case of SOAPFaults, a CXF web service will create a separate outbound error handling chain and the client will create an inbound error handling chain.
Writing an interceptor is relatively simple. Your interceptor needs to extend from either the AbstractPhaseInterceptor or one of its many subclasses such as AbstractSoapInterceptor.
The most important thing you should notice is the constructor: it defines the phase name for your interceptor. When you specify the phase, your interceptor is ordered according to the phase in the chain.
Most of the time you will want to extend from sub-classes of AbstractPhaseInterceptor. For example, using the SoapHeaderInterceptor you can access more specific information such as the SOAP Header.
For example the following Interceptor scans through the SOAP header:
You can also add information to the SOAP header using the message.getHeaders().add(header) method of the SoapMessage class.
In this example we have just added this header:
Here's a custom Interceptor that extends AbstractLoggingInterceptor, providing a log of the SOAP Message which can be printed or stored somewhere if necessary: