Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 119 ยท Servlets and JSP

SOAP Web Services and JAX-WS

Understand SOAP web services in Java - the envelope, WSDL contract, Faults, JAX-WS server and client code, contract-first versus code-first, and when SOAP beats REST.

Not every web service speaks JSON over REST. Banks, insurers, governments, telecom operators and big ERP systems still expose thousands of services through SOAP, an XML-based messaging protocol with a machine-readable contract. If you integrate with such a system, you will be handed a WSDL file, not an API documentation page, and you will use JAX-WS (Java API for XML Web Services, now Jakarta XML Web Services, package jakarta.xml.ws) to call it or to build a service of your own.

This lesson explains what a SOAP message contains, what a WSDL describes, how Faults carry errors, how a JAX-WS service and client look in real code, and how SOAP compares with the REST style you already know. The JAX-WS runtime is not on this course's code runner (it left the JDK in Java 11), so real JAX-WS code is read-only, while runnable examples use the XML tools that are in the JDK to build and parse real SOAP envelopes and to run a small SOAP endpoint on the loopback address.

What SOAP is

SOAP (originally Simple Object Access Protocol, today just a name) defines an envelope around an XML payload. It is independent of the transport: almost always HTTP POST, sometimes JMS or SMTP. A SOAP 1.1 message has this structure:

XML
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>   <!-- optional: security tokens, transaction ids, routing -->
  </soap:Header>
  <soap:Body>     <!-- exactly one payload: the operation call, its response, or a Fault -->
  </soap:Body>
</soap:Envelope>

The Header carries metadata that is not part of the business operation: authentication (WS-Security), correlation ids, reliable-messaging data. The Body carries the operation, named after the method being called, with namespaced child elements for the parameters. XML namespaces are essential: they let a message mix vocabularies without name clashes, and they identify the operation uniquely.

The two XML libraries in the JDK that you need are the DOM parser and XPath. This program builds the envelope above with DOM, prints it, then reads the operation, a parameter and a header value back with namespace-aware XPath, which is what every SOAP engine does under the hood:

Java Building and reading a SOAP envelope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice disallow-doctype-decl on the parser: SOAP endpoints accept XML from strangers, so they must switch off DTDs to avoid XXE (XML External Entity) attacks.

The WSDL contract

A WSDL (Web Services Description Language) document is the contract of a SOAP service: which operations exist, what messages they exchange, and where the service lives. Tools read it to generate client code, and testers like SoapUI read it to build requests. A WSDL has these parts:

Element Describes
<types> the XML Schema (XSD) of all messages and data types
<message> named inputs and outputs of an operation
<portType> the abstract interface: a list of operations (the "Java interface")
<binding> how that interface travels: SOAP 1.1 or 1.2, document or RPC style, the encoding
<service> / <port> the concrete endpoint address (URL)
XML
<definitions name="BookService" targetNamespace="http://example.com/books"
             xmlns="http://schemas.xmlsoap.org/wsdl/"
             xmlns:tns="http://example.com/books"
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
             xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <types>
    <xsd:schema targetNamespace="http://example.com/books">
      <xsd:element name="GetBookPrice"><xsd:complexType><xsd:sequence>
        <xsd:element name="isbn" type="xsd:string"/>
      </xsd:sequence></xsd:complexType></xsd:element>
      <xsd:element name="GetBookPriceResponse"><xsd:complexType><xsd:sequence>
        <xsd:element name="return" type="xsd:double"/>
      </xsd:sequence></xsd:complexType></xsd:element>
    </xsd:schema>
  </types>
  <message name="GetBookPriceIn"><part name="parameters" element="tns:GetBookPrice"/></message>
  <message name="GetBookPriceOut"><part name="parameters" element="tns:GetBookPriceResponse"/></message>
  <portType name="BookPort">
    <operation name="GetBookPrice">
      <input message="tns:GetBookPriceIn"/><output message="tns:GetBookPriceOut"/>
    </operation>
  </portType>
  <binding name="BookBinding" type="tns:BookPort">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="GetBookPrice">
      <soap:operation soapAction=""/>
      <input><soap:body use="literal"/></input><output><soap:body use="literal"/></output>
    </operation>
  </binding>
  <service name="BookService">
    <port name="BookPort" binding="tns:BookBinding">
      <soap:address location="https://api.example.com/ws/books"/>
    </port>
  </service>
</definitions>

Modern services use document/literal style: the body contains one schema-defined element, exactly as in our example. The older RPC/encoded style is deprecated and should be avoided. The WSDL is usually served at the service URL plus ?wsdl.

Faults: SOAP's error model

A service reports an error by returning a Fault in the Body, usually with HTTP status 500. In SOAP 1.1 a Fault has a faultcode (soap:Client if the request was wrong, soap:Server if the service failed), a faultstring and an optional detail with structured data. SOAP 1.2 renames these to Code, Reason and Detail. In JAX-WS a Java exception annotated with @WebFault is mapped to a Fault, and the generated client rethrows it as the same exception type, so errors cross the wire as typed exceptions rather than status codes.

A JAX-WS service

Code-first development means you write the Java class and let the runtime generate the WSDL. This is real JAX-WS code (Jakarta XML Web Services 4.0, with Metro or Apache CXF as the implementation); it is shown read-only because the library is not available in the runner:

Java
import jakarta.jws.WebMethod;
import jakarta.jws.WebParam;
import jakarta.jws.WebResult;
import jakarta.jws.WebService;
import jakarta.xml.ws.Endpoint;

@WebService(serviceName = "BookService", targetNamespace = "http://example.com/books")
public class BookService {

    @WebMethod(operationName = "GetBookPrice")
    @WebResult(name = "return")
    public double getBookPrice(@WebParam(name = "isbn") String isbn) throws UnknownIsbnException {
        return catalog.priceOf(isbn).orElseThrow(() -> new UnknownIsbnException(isbn));
    }

    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/ws/books", new BookService());
        // WSDL is now at http://localhost:8080/ws/books?wsdl
    }
}

@WebFault(name = "UnknownIsbn")
public class UnknownIsbnException extends Exception {
    private final String isbn;
    public UnknownIsbnException(String isbn) { super("Unknown ISBN " + isbn); this.isbn = isbn; }
    public String getIsbn() { return isbn; }       // becomes part of the Fault detail
}

Key annotations: @WebService marks the class (or an interface and its implementation), @WebMethod customizes an operation, @WebParam and @WebResult name the XML elements, and @SOAPBinding(style = DOCUMENT) selects the style. Endpoint.publish starts a built-in HTTP server for development; in production the same class is deployed in a WAR on a Jakarta EE server, or exposed with Spring through Apache CXF or Spring Web Services.

Java object graphs become XML through JAXB (Jakarta XML Binding): classes annotated with @XmlRootElement, @XmlElement or @XmlType are marshalled automatically.

Inside, the engine does what the next program does. It decodes the Body, finds the method named after the operation, converts the parameters, calls it, and wraps the result or the exception in an envelope. The service class is plain Java, the engine is about 40 lines, and a standard HttpClient plays the role of the client:

Java A SOAP endpoint and client over HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The unknown ISBN produces a soap:Client Fault with HTTP status 500, and an unknown operation does too, while the successful calls return status 200. The request a &amp; b shows why a real engine escapes XML text properly.

Calling a service from Java

When you consume a service, you rarely write envelopes by hand. Contract-first development starts from the WSDL: a tool generates Java classes (the JAX-B types, a service interface, a Service subclass) and you call remote methods like local ones.

Terminal
# Maven plugin or the CLI tool that ships with the implementation
wsimport -keep -p com.example.books.client https://api.example.com/ws/books?wsdl
Java
BookService service = new BookService_Service().getBookPort();      // generated classes

// Optional: point to another URL, add timeouts
BindingProvider provider = (BindingProvider) service;
provider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://staging.example.com/ws/books");
provider.getRequestContext().put("com.sun.xml.ws.request.timeout", 5_000);       // Metro-specific key

try {
    double price = service.getBookPrice("978-0-441-17271-9");
    System.out.println(price);
} catch (UnknownIsbnException e) {                                    // the Fault, as a typed exception
    System.out.println("No such ISBN: " + e.getIsbn());
}

Contract-first has a big advantage for integration: both sides agree on the XSD and WSDL first, and generated code makes breaking changes visible at compile time. Code-first is quicker for internal services, but the generated contract can change when you refactor, so freeze the WSDL once clients depend on it.

Handlers and WS-Security

JAX-WS lets you plug handlers into the message path: a SOAPHandler sees the whole envelope (add a header, log the XML, validate a token), and a LogicalHandler sees only the payload. This is the SOAP counterpart of a servlet filter or JAX-RS provider. Security usually follows the WS-Security standards, which add signed and encrypted headers (UsernameToken, X.509 signatures, SAML assertions) so that a message stays protected even when it passes through intermediaries. Implementations such as Apache CXF with WSS4J configure this with policies rather than code.

SOAP versus REST

Aspect SOAP / JAX-WS REST / JAX-RS
Format XML only JSON, XML, anything
Contract WSDL + XSD, strict and generated OpenAPI (optional)
Style operations (RPC-like) resources and HTTP verbs
Transport HTTP, JMS, SMTP HTTP
Errors Faults (typed) HTTP status codes
Standards for security, transactions, reliable messaging WS-* family HTTPS, OAuth 2, API gateways
Caching difficult (always POST) HTTP caching works
Payload size larger smaller

Choose SOAP when the partner mandates it, when you need formal contracts and WS-Security across intermediaries, or in legacy and regulated ecosystems. Choose REST for new public APIs, mobile and browser clients, and anything that benefits from HTTP caching and lightweight JSON. Many companies keep both: a REST facade for new consumers in front of the same business code. To email the results of such services, see the next lesson on Jakarta Mail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which part of a SOAP message carries the operation being called?

    The Body contains exactly one payload (the request named after the operation, the response, or a Fault). The Header holds metadata such as security tokens.
  2. 2. What does a WSDL file describe?

    A WSDL is the machine-readable contract: schema types, operations (portType), the SOAP binding and the endpoint address.
  3. 3. A client sends a request with an invalid ISBN and the service returns a Fault. Which faultcode fits best in SOAP 1.1?

    soap:Client means the request was at fault, soap:Server means the service itself failed. Faults normally travel with HTTP 500.
  4. 4. Why should a SOAP endpoint disable DTD processing in its XML parser?

    An attacker can declare an external entity that reads local files or calls internal URLs. Turning off doctype declarations closes that hole.
  5. 5. What is the difference between contract-first and code-first?

    Contract-first fixes the agreement before any implementation exists, which suits multi-party integrations. Code-first is quicker but the contract may drift as the code changes.

Summary

  • SOAP wraps XML in an Envelope with an optional Header (metadata, WS-Security) and one Body (call, response or Fault).
  • A WSDL plus XSD is the strict contract: types, messages, port type (operations), binding (SOAP style) and service address.
  • Errors are Faults (soap:Client or soap:Server, usually HTTP 500); JAX-WS maps them to @WebFault exceptions.
  • JAX-WS / Jakarta XML Web Services uses @WebService, @WebMethod, @WebParam and Endpoint.publish; JAXB maps Java objects to XML; wsimport generates clients from a WSDL.
  • Handlers add cross-cutting behavior; always parse untrusted XML with DTDs disabled.
  • Choose SOAP for mandated, contract-heavy or WS-Security integrations and REST for most new APIs.

Next: Sending Email with Jakarta Mail shows another protocol-level integration, this time over SMTP.