Using JAXB and JAX-WS for service with custom headers

Since the introduction of the JAX-WS in Java EE building SOAP web-services have never been easier (as compared to i.e. Spring WS). Just a few annotations and you are up and running. Disadvantage of this all is that it always goes from a Contract first or Java first approach. While in a lot of environments this is the case, situations are there when its a mixed case.

Just recently I ran into the mixed case. Needed to replace an existing service that did not have any WSDL’s but the XSD’s for the payload was there. The following are the steps I executed to implement the new service from the existing XSD’s and included inbound and outbound headers.

Generating the ObjectFactories from the supplied XSD’s is simple in maven just add the following snippet to the your maven pom file:

That is all to have the JAXB files generated. The bindings file I specified was allows you to customize the generated classes. I tend to convert the xsd:DateTime to JodaTime, but that is just me.

Next the definition of the JAX-WS services. On the Internet there are a lot of guides available to get started with JAX-WS. No point in getting into that. I found that information on dealing with headers is mixed.

All the solutions provided will do the trick to get headers in the message. What you do not find a lot is a solution that uses the @WebParam annotation in the argument list of the web service. The annotation has a two important fields for header support; header and mode.

Setting  the header field to true, will add this to the header part of the soap message. the mode flag allows the following values:

  • IN
    Inbound
  • OUT
    Outbound
  • INOUT
    In and Outbound.

The first two are easy to use. the last,** INOUT** has a bit more to it.

When using the WebParam.Mode.INOUT value changes are high that the container you are running is not able to generate the WSDL and XSD files. The error you get is ambiguous. End result your WSDL is not generated hence the service is not available.  The key when using the INOUT mode is the generic class javax.xml.ws.Holder. When the parameter is placed inside this type. The WSDL is generated correctly.

Resulting @WebMethod method:

Access to the values in the header object is straight forward. when you modify the values the response contains the modified values. With this solution there is no need to write custom  SOAPHandler implementations for headers.

The generated WSDL will be: As you can see a nicely generated WSDL that contains information about the headers that are expected and returned.

There is however 1 minor disadvantage with this solution. When an exception is thrown you do not have access to the headers anymore.  I have a solution for this, implementation of a Handler that intercepts the request, stores the header and modifies the fault response in the handleFault method. But that is a subject for an other post.