Using a Message Handler to alter the SOAP Header in a Web Service Client

Sometimes you need to insert information in the soap header when calling a web service. Perhaps the service needs authentication information that needs to be set.
This example shows how to set the security information for a Web Service that is deployed on a Weblogic server using JAX-WS and SAAJ.

First we need to create the actual handler which implements the SOAPHandler interface.
Next we need to create the class that implements the HandlerResolver interface. This class decides what handlers should be called and in what specific order. The handler above is added to this class.
Finally we need to add the HandlerResolver instance to the Web Service Client.

By default the SOAP header is empty, but this is what we want the header to look like on the outbound call (the call to the web service):

In our handler we need to do the implementation of a few methods but it is only the handleMessage() method that is of essence here.
This is what our handler class looks like:

The handler resolver that is to contain the SOAP handler above looks like this:

Finally we need to add the handler resolver to our web service client class.

To find out how to generate the web service client classes check out this example:

Create a Web Service Client with JAX-WS

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?