Skip to content
VirtualLP Virtual Learning Platform

SOAP Messaging Architecture, SOAP Header and Client-side Handlers

14 min read Topic 5 of 34

A SOAP (originally Simple Object Access Protocol) message may pass through several programs before reaching the service. One program may check access. Another may record the request.

The Header carries extra message details. A handler is code that runs while a message enters or leaves a JAX-WS (Java API for XML Web Services) application. It can read or change the message, record it or stop it.

letter through an office

A letter goes from you → the security desk (checks your ID label) → the mail room (writes it in the register) → the manager (reads the letter). The security desk and mail room only look at the labels on the envelope; only the manager opens the letter inside. In SOAP, the labels are headers, the letter is the body, and the desks in between are intermediaries.

SOAP messaging architecture

SOAP node

A SOAP node is software that sends, receives or passes on a SOAP message. It may be the initial sender, an intermediary on the way, or the final receiver.

flowchart LR
    S[Initial SOAP sender<br/>client application] -->|SOAP message| I1[Intermediary 1<br/>security gateway]
    I1 -->|processes its headers,<br/>forwards| I2[Intermediary 2<br/>logging / routing]
    I2 --> R[Ultimate SOAP receiver<br/>web service]
    R -. response .-> S
Node What it does
Initial sender Creates the message (envelope, headers, body).
Intermediary Receives the message, handles the headers meant for it, may remove or add headers, and passes it on. It must not change the body.
Ultimate receiver The final web service. It handles the body and any headers meant for it, and sends back the response or a fault.

The message path lists the nodes a message passes through. Shared services can check access, record requests or route messages. This avoids repeating the same code in every service.

Message exchange patterns

  • One-way – sender → receiver, no response.
  • Request–response – the usual pattern: send a request and wait for the answer over HTTP (Hypertext Transfer Protocol).
  • Asynchronous with callbacks – the reply comes later, to a different address, using WS-Addressing ReplyTo headers (like "call me back on this number").

The SOAP header in detail

The optional <Header> contains header blocks. Each block is an XML (Extensible Markup Language) element. SOAP attributes say which node should process it and whether that node must understand it.

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
               xmlns:sec="http://virtuallp.com/security"
               xmlns:txn="http://virtuallp.com/txn">
  <soap:Header>
    <sec:Credentials soap:role="http://virtuallp.com/roles/gateway"
                     soap:mustUnderstand="true">
      <sec:username>priya</sec:username>
      <sec:token>8f2a…</sec:token>
    </sec:Credentials>
    <txn:TransactionId soap:mustUnderstand="false">TXN-2026-118</txn:TransactionId>
  </soap:Header>
  <soap:Body> … </soap:Body>
</soap:Envelope>

Here there are two header blocks:

  • Credentials – meant for the gateway (role), and it must be understood.
  • TransactionId – optional information; a node may ignore it.

Header attributes

Attribute (SOAP 1.2 / 1.1) Values Meaning
role / actor A URI (Uniform Resource Identifier) Which node should handle this header. Special values: …/next (the next node), …/ultimateReceiver (the final service), …/none (nobody).
mustUnderstand true/false (1/0) If true, the node it is meant for must handle it – or return a MustUnderstand fault.
relay (SOAP 1.2 only) true/false Whether an intermediary should pass on a header it did not handle.
encodingStyle A URI The rules used to write the data in the block.
mustUnderstand rule

If a header block meant for a node has mustUnderstand="true" and that node does not recognise it, the node must stop and return a SOAP Fault with code MustUnderstand. This makes sure, for example, that a security header is never silently ignored.

Common uses of headers (WS-* standards)

Standard What the header carries
WS-Security Usernames and tokens, X.509 certificates, digital signatures, encryption
WS-Addressing To, ReplyTo, MessageID, Action – where the message goes and where replies go
WS-ReliableMessaging Sequence numbers and acknowledgements, so no message is lost
WS-AtomicTransaction Transaction details, so several services succeed or fail together
Custom Session IDs, API (Application Programming Interface) keys, correlation IDs (to trace one request across services), language

SOAP handlers in JAX-WS

Handler

A handler is code that JAX-WS calls while a message enters or leaves the application. It can read or change the message. Several handlers used in order form a handler chain.

There are two kinds:

Handler type Interface Can see Typical use
Logical handler LogicalHandler<LogicalMessageContext> Only the content (body) Checking or changing the data
Protocol (SOAP) handler SOAPHandler<SOAPMessageContext> The whole SOAP message, including headers Security tokens, logging, adding or reading headers
sequenceDiagram
    participant App as Client code
    participant H1 as SOAPHandler (outbound)
    participant Net as Network
    participant H2 as SOAPHandler (inbound)
    App->>H1: port.getMarks("R101")
    H1->>H1: add <Credentials> header
    H1->>Net: SOAP request
    Net-->>H2: SOAP response
    H2->>H2: log / check response headers
    H2-->>App: result

Order matters: for outgoing messages, logical handlers run first, then SOAP handlers. For incoming messages, SOAP handlers run first.

Handler methods

Method Called when
handleMessage(context) For every normal message (in and out). Return true to continue, false to stop the chain.
handleFault(context) When a SOAP fault is being processed.
close(context) After the exchange is finished – for clean-up.
getHeaders() Returns the names (QNames) of the headers this handler understands – used for the mustUnderstand check.

context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY) tells you the direction: true = going out, false = coming in.

Writing a client-side SOAP handler

This handler adds a login header to every outgoing request and prints every message:

package com.virtuallp.client;

import java.util.Collections;
import java.util.Set;
import javax.xml.namespace.QName;
import jakarta.xml.soap.*;
import jakarta.xml.ws.handler.MessageContext;
import jakarta.xml.ws.handler.soap.SOAPHandler;
import jakarta.xml.ws.handler.soap.SOAPMessageContext;

public class AuthHeaderHandler implements SOAPHandler<SOAPMessageContext> {

    private static final String NS = "http://virtuallp.com/security";

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        try {
            SOAPMessage message = context.getMessage();
            if (outbound) {
                SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
                SOAPHeader header = envelope.getHeader();
                if (header == null) header = envelope.addHeader();

                SOAPHeaderElement creds = header.addHeaderElement(new QName(NS, "Credentials", "sec"));
                creds.setMustUnderstand(true);
                creds.addChildElement("username", "sec").addTextNode("priya");
                creds.addChildElement("token", "sec").addTextNode("8f2a-demo-token");
                message.saveChanges();
            }
            System.out.println(outbound ? "\n>>> Outbound message:" : "\n<<< Inbound message:");
            message.writeTo(System.out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;   // continue processing the chain
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        System.err.println("SOAP fault received");
        return true;
    }

    @Override public void close(MessageContext context) { }

    @Override
    public Set<QName> getHeaders() {
        return Collections.singleton(new QName(NS, "Credentials"));
    }
}

What it does, step by step:

  1. Checks the direction. If the message is going out…
  2. …it gets (or creates) the SOAP Header,
  3. adds a Credentials block with a username and token, marked mustUnderstand,
  4. saves the change.
  5. For every message (in or out) it prints the full XML – useful for learning and debugging.
  6. Returns true so the next handler (or the network) continues.

Registering the handler on the client

In code (programmatically) – add it to the proxy's handler chain:

StudentService service = new StudentService();
StudentPort port = service.getStudentPort();

BindingProvider bp = (BindingProvider) port;
List<Handler> chain = bp.getBinding().getHandlerChain();
chain.add(new AuthHeaderHandler());
bp.getBinding().setHandlerChain(chain);   // must set the list back!

System.out.println(port.getMarks("R101"));
Common mistake

getHandlerChain() returns a copy. If you forget setHandlerChain(chain), your handler is never used.

In a file (declaratively) – put @HandlerChain(file = "handlers.xml") on the service class:

<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
  <handler-chain>
    <handler>
      <handler-class>com.virtuallp.client.AuthHeaderHandler</handler-class>
    </handler>
  </handler-chain>
</handler-chains>

Reading the header on the server

A server-side handler reads the Credentials header and checks the token. If it is wrong, the handler can throw a SOAPFaultException. The service operation should not run for a rejected request.

In the real world

Handlers are how companies add WS-Security, audit logs and correlation IDs to hundreds of services without changing their code. Modern REST (Representational State Transfer) systems use the same idea under other names: filters (Servlet, JAX-RS (Java API for RESTful Web Services) ClientRequestFilter), interceptors (Spring) or middleware (Laravel, Express).

Summary

  • SOAP messages travel from an initial sender through optional intermediaries to the ultimate receiver; intermediaries handle headers but never the body.
  • Header blocks use role/actor, mustUnderstand and (SOAP 1.2) relay to control who handles them.
  • JAX-WS handlers catch messages: logical handlers see only the content, SOAP handlers see the full envelope.
  • Handler methods: handleMessage, handleFault, close, getHeaders; register them in a handler chain in code or with @HandlerChain.

Practice questions

  1. Explain the SOAP messaging architecture with a diagram showing sender, intermediaries and receiver.
  2. What is a SOAP header? Explain the actor/role and mustUnderstand attributes.
  3. What happens when a node does not understand a header marked mustUnderstand="true"?
  4. Differentiate between logical handlers and SOAP handlers.
  5. Write a client-side SOAP handler that adds a header to every outgoing request.
  6. Explain the methods of the SOAPHandler interface.

Create a free account to track your progress and unlock virtual labs.