Copyrights @ Journal 2014 - Designed By Templateism - SEO Plugin by MyBloggerLab

Wednesday, August 20, 2008

JAX-WS and Custom SOAP Header


Recently, during my transition to JAX-WS, a work in hand made me use Custom Soap headers in design in a JAX-WS implementation. Pertaining same, my recent conversations with friend, we need a quick sample how to use custom headers with JAX-WS.

JAX-WS by Sun’s specifications support custom soap headers. It is as easier as .Net or webMethods. It supports the WSDL with SOAP header information also.

As per W3C, “The Representation header block is designed to allow applications to carry a representation of a Web resource in a SOAP message”. 


It is not limited or only used by system processing, applications can use it for several reasons which include the access restriction, avoiding payload browse, and also overhead (accessing headers is faster than body). So it is perfectly allowed to use SOAP custom headers, philosophy being soap:body should contain only the payload, all routing headers should be used as soap:headers.

Here is how you do it.

Change your soapbinding annotation to DOCUMENT, by default it is DOCUMENT but I made it explicit because it was giving some error.

@WebService(name = "GoodbyeWorldWS", 
targetNamespace="http://webservice_producer/goodbyeworld") @SOAPBinding(style = SOAPBinding.Style.DOCUMENT)

Add new @WebParam with header=true. You can also set the Mode to INOUT so that header value is returned to consumer too. You can access the headers via the WebParam name specified in the name attribute.

public String sayGoodbye(
   @WebParam(name="message") String message,
   /*Add header element */
   @WebParam(name="header",mode=Mode.IN, header=true) String headerElement) 
System.out.println("SOAP HEADER VALUE" + headerElement); return ".Goodbye."; }

Here is how the WSDL looks like, it has the soap:header added.

    <soap:body parts="sayGoodbye" use="literal" /> 
  <soap:header message="tns:GoodbyeWorldWS_sayGoodbye" part="header" use="literal" />

Here is the C# code to invoke it.

GoodbyeWorldWSService.GoodbyeWorldWSService ws = 
      new ConsoleApplication2.GoodbyeWorldWSService.GoodbyeWorldWSService();
GoodbyeWorldWSService.sayGoodbye input = 
     new ConsoleApplication2.GoodbyeWorldWSService.sayGoodbye();
input.message = "JAX WS support Body";
ws.header = new ConsoleApplication2.GoodbyeWorldWSService.@string();
ws.header.Text = new String[] { "JAX WS Supports Headers" };
GoodbyeWorldWSService.sayGoodbyeResponse output = ws.sayGoodbye(input);

Here is how the SOAP message  looks like in server log

22:07:21,187 INFO [STDOUT]
<soap:Envelope xmlns:soap=
  <header xmlns="http://webservice_producer/goodbyeworld">
      JAX WS Supports Headers
  <sayGoodbye xmlns="http://webservice_producer/goodbyeworld">
     <message xmlns="">JAX WS support Body</message>