杰瑞科技汇

Java WebService SOAP如何快速入门?

Of course! Let's dive into creating a Java Web Service using SOAP. This is a classic and robust way to enable communication between different applications over a network.

Java WebService SOAP如何快速入门?-图1
(图片来源网络,侵删)

We'll cover:

  1. What is SOAP? - A quick refresher.
  2. Core Java Technologies for SOAP - The main players (JAX-WS and JAXB).
  3. Step-by-Step Tutorial: Creating a SOAP Web Service - A complete, practical example.
  4. Consuming the SOAP Web Service - How to call the service from a client.
  5. Best Practices and Modern Alternatives - When to use SOAP and what else is out there.

What is SOAP?

SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in web services. It's a XML-based protocol, meaning all messages are formatted in XML.

Key Characteristics:

  • Protocol: It has strict rules and standards (defined by W3C).
  • XML-based: Messages are human-readable but verbose.
  • Platform and Language Independent: A Java service can be consumed by a .NET, Python, or any other client that understands SOAP.
  • Highly Extensible: Supports WS-Security, WS-ReliableMessaging, WS-Addressing, etc., for advanced enterprise features.
  • Stateless: Each SOAP message is an independent unit of communication.

A Typical SOAP Message looks like this:

Java WebService SOAP如何快速入门?-图2
(图片来源网络,侵删)
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
    <!-- Optional header for security, transactions, etc. -->
  </soap:Header>
  <soap:Body>
    <m:GetStockPrice xmlns:m="http://www.example.org/stock">
      <m:StockName>IBM</m:StockName>
    </m:GetStockPrice>
  </soap:Body>
</soap:Envelope>

Core Java Technologies for SOAP

Modern Java development for SOAP relies on two main APIs:

a) JAX-WS (Java API for XML Web Services)

This is the standard API for creating SOAP web services in Java. It provides a set of annotations and APIs to simplify the development process. You don't have to write XML or low-level networking code yourself.

  • Key Annotations:
    • @WebService: Marks a Java class as a web service endpoint.
    • @WebMethod: Marks a Java method as a web service operation.
    • @WebParam: Maps a method parameter to a request message part.
    • @SOAPBinding: Defines the SOAP binding style (e.g., document/literal).

b) JAXB (Java Architecture for XML Binding)

JAXB is used to map Java objects to XML representations and vice versa. JAX-WS uses JAXB "under the hood" to convert your Java method parameters and return values into the SOAP XML body and back.

  • Key Annotations:
    • @XmlRootElement: Maps a class to an XML root element.
    • @XmlElement: Maps a field/property to an XML element.

You don't need to configure JAXB manually when using JAX-WS in modern Java (6+), as it's included by default.

Java WebService SOAP如何快速入门?-图3
(图片来源网络,侵删)

Step-by-Step Tutorial: Creating a SOAP Web Service

We will use Maven to manage our project and Apache CXF, a popular implementation of JAX-WS, to run our service.

Step 1: Create a Maven Project

Create a new Maven project (e.g., using your IDE or the command line). Your pom.xml file is the most important part.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>java-soap-service</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cxf.version>3.4.5</cxf.version>
    </properties>
    <dependencies>
        <!-- JAX-WS API (for annotations) -->
        <dependency>
            <groupId>jakarta.xml.ws</groupId>
            <artifactId>jakarta.xml.ws-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <!-- Apache CXF Implementation (to run the service) -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>${cxf.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 2: Create the Service Endpoint Interface (SEI)

This is a Java interface that defines the contract for your web service. It contains the methods that will be exposed as SOAP operations.

src/main/java/com/example/HelloWorld.java

package com.example;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
// This annotation marks this interface as a Web Service.
@WebService
// Defines the SOAP binding style. DOCUMENT/LITERAL is the most common.
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL)
public interface HelloWorld {
    // This annotation exposes the method as a web service operation.
    @WebMethod
    String sayHello(@WebParam(name = "name") String name);
}

Step 3: Create the Service Implementation Bean (SIB)

This is the concrete class that implements the HelloWorld interface. It contains the actual business logic.

src/main/java/com/example/HelloWorldImpl.java

package com.example;
import javax.jws.WebService;
@WebService(endpointInterface = "com.example.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name + "!";
    }
}
  • @WebService(endpointInterface = "com.example.HelloWorld") is crucial. It tells JAX-WS that this class implements the service contract defined by the HelloWorld interface.

Step 4: Create a Publisher to Deploy the Service

This class will use Apache CXF to start a simple HTTP server and publish our service endpoint on it.

src/main/java/com/example/HelloWorldPublisher.java

package com.example;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class HelloWorldPublisher {
    public static void main(String[] args) {
        // Create a JAX-WS server factory
        JaxWsServerFactoryBean serverFactory = new JaxWsServerFactoryBean();
        // Set the service implementation bean
        serverFactory.setServiceBean(new HelloWorldImpl());
        // Set the address (URL) where the service will be published
        serverFactory.setAddress("http://localhost:8888/ws/hello");
        // Create and start the server
        serverFactory.create();
        System.out.println("Server is ready at http://localhost:8888/ws/hello");
        System.out.println("WSDL is available at http://localhost:8888/ws/hello?wsdl");
    }
}

Step 5: Run the Service

Execute the main method in HelloWorldPublisher.java.

You should see the output:

Server is ready at http://localhost:8888/ws/hello
WSDL is available at http://localhost:8888/ws/hello?wsdl

Congratulations! Your SOAP web service is now running.

  • Open a web browser and go to http://localhost:8888/ws/hello?wsdl. You will see the WSDL (Web Services Description Language) file, which is the XML contract that describes your service to potential clients.

Consuming the SOAP Web Service

Now, let's create a Java client to call our service.

Step 1: Create a Maven Client Project

Create a new Maven project. You can reuse the pom.xml from the server project, as it contains the necessary dependencies.

Step 2: Create

分享:
扫描分享到社交APP
上一篇
下一篇